﻿using System;
using System.IO;
using System.Xml.Serialization;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Exchange.WebServices.Data;
using ChucksClassLibrary;

namespace AREQWinService
{
    public partial class AREQService : ServiceBase
    {
        static ChucksMessagingHandler ChucksMH = new ChucksMessagingHandler();
        static ChucksConvertTime ChucksCT = new ChucksConvertTime();
        static ChucksDataHandler ChucksDH = new ChucksDataHandler();
        static ChucksWebServiceHandler ChucksWSH = new ChucksWebServiceHandler();
        static ChucksFileHandler ChucksFH = new ChucksFileHandler();

        private System.Timers.Timer DrainQueueTimer = new System.Timers.Timer(); 
        private System.Timers.Timer ProcessACARSTimer = new System.Timers.Timer();
        private System.Timers.Timer AreqSubscriptionsTimer = new System.Timers.Timer();

        public static string ACARSWatcherPath = @"\\IBPFTPROD\sabre\FLTCTRL\QUEUES\AIRCOM\AREQ\RECEIVE";

        static string OutputFilePath = "";
        static Queue<string> FilenamesQueue = new Queue<string>();
        static Queue<string> TempQueue = new Queue<string>();
        static DateTime ACMREQTimeStamp = DateTime.Now;
        static DateTime AREQStatsTimeStamp = DateTime.Now;
        static Int16 AREQStatsACARS = 0;
        static Int16 AREQStatsEMAIL = 0;
        static List<objCounters> Counters = new List<objCounters>();
        static List<FileData> lstProcessedACARSFiles = new List<FileData>();
        static List<FileData> lstProcessedEMAILFiles = new List<FileData>();
        static ChucksClassLibrary.prodLocations_v2.Location[] arrLocations = ChucksWSH.FillLocations();

        //Create Event Log;
        static EventLog myLog = new EventLog();

        #region help message
        static string msgGouge = "** AREQ USERS GUIDE **," +
                                  "IS NOW AVAILABLE IN," +
                                  "JBDOCS .. MANUAL SUPP," +
                                  "PLEASE REFER TO THIS," +
                                  "GUIDE FOR LATEST USAGE,," +
                                  "** NEW COMMAND **,," +
                                  "Preflight," +
                                  "PREFLIGHT <FltNum><Date>," +
                                  "  ex.  PREFLIGHT 615," +
                                  "** NEW COMMAND **,," +
                                  "Jetblue Flights," +
                                  "JBFLTS <CITYPAIR><Date>," +
                                  "  ex.  JBFLTS JFKJAX," +
                                  "Schedules," +
                                  "SKED <EmpID><PIN>," +
                                  "  ex.  SKED 12345XXXX," +
                                  "Pairing Legs," +
                                  "PAIRING <Pairing> <Date>," +
                                  "  ex.  PAIRING J2344C 1/30/11," +
                                  "Inbound Flights," +
                                  "INBOUND <FltNum>," +
                                  "  ex.  INBOUND 610," +
                                  "DOOR CODES," +
                                  "DOORS <City>," +
                                  "  ex.  DOORS MCO," +
                                  "FLTSUM <FltNum> <Date>," +
                                  "  ex.  FTLSUM 610," +
                                  "TAIL <TailNum> <Date>," +
                                  "  ex.  TAIL 503," +
                                  "LOADS <FltNum> <Date>," +
                                  "  ex.  LOADS 610," +
                                  "BRIEF <City City>," +
                                  " ex. BRIEF JFK LGA EWR," +
                                  "PROGRAMS <City>," +
                                  " ex. PROGRAMS JFK," +
                                  "COMMANDS," +
                                  "  ex. COMMANDS," +
                                  "EDCT <FltNum>," +
                                  "  ex. EDCT 610," +
                                  "TURNS <City> [Time(HHMM)L]," +
                                  "  ex. TURNS JFK 0800," +
                                  "  or  TURNS JFK," +
                                  "TIMES <FltNum> <Date>," +
                                  "  ex. TIMES 610 10-01-2007," +
                                  "  or  TIMES 610," +
                                  "TAXI <City>," +
                                  "  ex. TAXI JFK," +
                                  "DELAYS <City>," +
                                  "  ex. DELAY JFK," +
                                  "CREW <FltNum> <Date>," +
                                  "  ex. CREW 610 10-01-2007," +
                                  "  or  CREW 610,," +
                                  "If you have suggestions," +
                                  "For this app pls email," +
                                  "charles.cook@jetblue.com";
        static string msgUnkERROR = ",There was an Unknown Err,," +  //comma delim string to be split by reged
                                    "PLEASE REFER TO THE," +
                                    "AREQ USERS GUIDE IN," +
                                    "JBDOCS .. MANUAL SUPP," +
                                    "pls email the details," +
                                    "to Chuck Cook at," +
                                    "charles.cook@jetblue.com,,";
        #endregion

        public AREQService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            //Log Setup and Start Events
            LogSetup();
            LogEvent("AREQService Started. In OnStart");
            DateTime CompiledDate = DateCompiled();
            Debug.WriteLine("DateCompiled: " + CompiledDate.ToString());
            LogEvent("DateCompiled: " + CompiledDate.ToString());


            InitCounters();


            // Create a new Timer with Interval set to 30 secs
            DrainQueueTimer.Elapsed += new System.Timers.ElapsedEventHandler(DrainQueue);
            DrainQueueTimer.Interval = (30 * 1000);
            // Reset time after each event.
            DrainQueueTimer.AutoReset = true;
            DrainQueueTimer.Enabled = true;
            DrainQueueTimer.Start();

            // Create a new Timer with Interval set to 20 secs
            ProcessACARSTimer.Elapsed += new System.Timers.ElapsedEventHandler(ManageACARSQueue);
            ProcessACARSTimer.Interval = (30 * 1000);
            // Reset time after each event.
            ProcessACARSTimer.AutoReset = true;
            ProcessACARSTimer.Enabled = true;
            ProcessACARSTimer.Start();

            // Create a new Timer with Interval set to 90 secs
            AreqSubscriptionsTimer.Elapsed += new System.Timers.ElapsedEventHandler(CheckAREQSubscriptions);
            AreqSubscriptionsTimer.Interval = (90 * 1000);
            // Reset time after each event.
            AreqSubscriptionsTimer.AutoReset = true;
            AreqSubscriptionsTimer.Enabled = true;
            AreqSubscriptionsTimer.Start();
        }
        protected override void OnStop()
        {
            DrainQueueTimer.Stop();
            ProcessACARSTimer.Stop();
            EventLog.WriteEntry("AREQ Service Stopped: In OnStop");
        }
        public static void LogSetup()
        {
            string evtSource = "Chucks AREQ Service";

            if (!EventLog.SourceExists(evtSource))
                EventLog.CreateEventSource(evtSource, "ChucksLogs");

            myLog.Source = evtSource;
            myLog.MaximumKilobytes = 5120;
            myLog.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 30);
        }
        public static void LogEvent(string message)
        {
            EventLogEntryType evtType;
            if (System.Text.RegularExpressions.Regex.Match(message, @"ERROR:").Success)
                evtType = EventLogEntryType.Warning;
            else
                evtType = EventLogEntryType.Information;

            myLog.WriteEntry(message, evtType);
        }
        // Needed for debugging
        internal void StartService()
        {
            //Used for debugging
            this.OnStart(null);

        }
        internal void StopService()
        {
            //Used for debugging
            this.OnStop();

        }

        private static void ManageACARSQueue(object source, EventArgs e)
        {
            FileCompare myFileCompare = new FileCompare();
            List<FileData> lstNewFiles = new List<FileData>();

            lstNewFiles = FastDirectoryEnumerator.EnumerateFiles(ACARSWatcherPath)
                .Where(x => x.CreationTime > DateTime.Now.AddMinutes(-2))
                .ToList();

            var queryDifferences = (from file in lstNewFiles
                                    select file).Except(lstProcessedACARSFiles, myFileCompare);

            foreach (FileData file in queryDifferences)
            {
                lstProcessedACARSFiles.Add(file);
                FilenamesQueue.Enqueue(file.Path);
                ACMREQTimeStamp = DateTime.Now;
            }

            //Deleted files from lstProcessedFiles older than 15mins
            lstProcessedACARSFiles.RemoveAll(x => x.CreationTime < DateTime.Now.AddMinutes(-15)); //Delete files older than 15 minutes from lstProcessedFiles

            Debug.Write("");
        }
        public static void DrainQueue(object source, EventArgs e)
        {
            try
            {
                #region AREQStats
                if (AREQStatsTimeStamp.Date != DateTime.Now.Date)
                {
                    //Clean old files from - This should be the same as the watcher path above, as well as the OUTLOOK VB Script****
                    ChucksFH.DeleteFiles(ACARSWatcherPath, 12);

                    //Reset Counter and sent stats email
                    System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();  //Create Mail Message Object
                    mail.To.Add("charles.cook@jetblue.com");

                    mail.Subject = "AREQ Daily Statistics";               // put subject here	
                    mail.Body = "These are the daily AREQ Statistics.\n"; // put body of email here
                    double ACARSPercent = ((double)AREQStatsACARS / ((double)AREQStatsACARS + (double)AREQStatsEMAIL));
                    double MailPercent = ((double)AREQStatsEMAIL / ((double)AREQStatsACARS + (double)AREQStatsEMAIL));
                    mail.Body += "Number of ACARS Requests: " + AREQStatsACARS.ToString() + " (" + ACARSPercent * 100 + "%)" + Environment.NewLine;
                    mail.Body += "Number of EMAIL Requests: " + AREQStatsEMAIL.ToString() + " (" + MailPercent * 100 + "%)" + Environment.NewLine;
                    mail.Body += "Total Requests: " + (AREQStatsEMAIL + AREQStatsACARS).ToString() + Environment.NewLine + Environment.NewLine;

                    var Sorted = Counters
                        .OrderByDescending(Counter => Counter.CurrentCount);

                    foreach (objCounters Counter in Sorted)
                    {
                        mail.Body += Counter.CounterName + ": " + Counter.CurrentCount + Environment.NewLine;
                    }

                    ChucksMH.SendMail(mail);

                    AREQStatsEMAIL = 0; AREQStatsACARS = 0;

                    foreach (objCounters Cntr in Counters)
                    {
                        Cntr.CurrentCount = 0;
                    }
                    AREQStatsTimeStamp = DateTime.Now;
                }
                #endregion

                lock (FilenamesQueue)
                {
                    while (FilenamesQueue.Count > 0)
                    {
                        TempQueue.Enqueue(FilenamesQueue.Dequeue());
                    }
                }
                CheckAcarsMonitorEmail();// Check for new messages now that the queue is empty

                while (TempQueue.Count > 0)
                {
                    ObjState StObj = new ObjState();
                    StObj.Filename = TempQueue.Dequeue();  //Load StObj Class with Variables to be passed in the threadpool
                    StObj.OutputFilename = OutputFilePath;

                    ParseACMREQMessage(StObj);
                    string TempFilename = System.IO.Path.GetFileName(StObj.Filename);

                    LogEvent(DateTime.Now.ToString() + " ACARS: " + AREQStatsACARS + " EMAIL: " + AREQStatsEMAIL + " Filename: " + TempFilename);
                    Debug.WriteLine(DateTime.Now.ToString() + " ACARS: " + AREQStatsACARS + " EMAIL: " + AREQStatsEMAIL + " Filename: " + TempFilename);

                }
                if (ACMREQTimeStamp < DateTime.Now.AddHours(-2))
                {
                    // Setup ACMREQ Notification EMail
                    System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();  //Create Mail Message Object
                    mail.To.Add("charles.cook@jetblue.com");
                    mail.Subject = "!! AREQ Server is DOWN !!";               // put subject here	
                    mail.Body = "No messages have been recieved on the AREQ Server." + Environment.NewLine; // put body of email here
                    mail.Body += "Last Message TimeStamp: " + ACMREQTimeStamp.ToString() + Environment.NewLine + Environment.NewLine;

                    ChucksMH.SendMail(mail);
                    ACMREQTimeStamp = DateTime.Now;
                }
            }
            catch (Exception err)
            {
                Debug.WriteLine("Thread Error" + err);
                LogEvent("ERROR: " + err.ToString() );
            }
        }
        public static void CheckAcarsMonitorEmail()
        {
            try
            {
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                service.Credentials = new NetworkCredential("acarsmonitor", "ChuckCookApps!", "jetblue");
                service.Url = new Uri("https://mail.jetblue.com/EWS/Exchange.asmx");
                
                //Fix TLS Error
                System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };

                FindItemsResults<Item> findResults = service.FindItems(
                    WellKnownFolderName.Inbox,
                    new ItemView(10));

                foreach (Item item in findResults.Items)
                {
                    if (item.Subject != null)
                    {
                        string UpperSubj = item.Subject.ToUpper(); //Convert to Upper for comparison
                        if (UpperSubj.Contains("AREQ")) //Create AREQ Drop File
                        {
                            string CleanSubject = "";
                            if (UpperSubj.StartsWith("RE: AREQ")) //allow replies without trimming subject
                            {
                                CleanSubject = UpperSubj.Substring(4, UpperSubj.Length - 4);
                            }
                            else
                                CleanSubject = UpperSubj;
                            EmailMessage message = EmailMessage.Bind(service, item.Id);
                            string NewFilename = ACARSWatcherPath + @"\" + DateTime.Now.ToString("ddMMyyyyHHmmssff") + "_Email.arq";
                            string AreqString = "<REPLYADDRESS>" + message.From.Address + "</REPLYADDRESS>" + Environment.NewLine +
                                "<AREQLINE>" + CleanSubject + "</AREQLINE>" + Environment.NewLine;

                            //Create File Drop
                            ChucksFH.WriteStringToFile(NewFilename, AreqString);
                        }
                        else if (UpperSubj.Contains("ACARS TEXT FROM")) //Reply To AREQ TEXT
                        {
                            EmailMessage message = EmailMessage.Bind(service, item.Id);

                            Regex rgxSubjLine = new Regex(@"ACARS\sTEXT\sFrom\sFlt:\s(?<FltNum>\w{4})\sTail:\s(?<TailNum>\w{3})", RegexOptions.Singleline);
                            Regex rgxReplyBody = new Regex(@"\*\*\*ReplyStart\r\n(?<ReplyMessage>.+)\r\n\*\*\*ReplyEnd", RegexOptions.Singleline);

                            Match mtchSubj = rgxSubjLine.Match(message.Subject);
                            Match mtchReplyBody = rgxReplyBody.Match(message.Body);

                            if ((mtchSubj.Success) && (mtchReplyBody.Success))
                            {
                                ChucksStringHander CSH = new ChucksStringHander();

                                string Tailnum = mtchSubj.Groups["TailNum"].Value;
                                string ReplyBody = mtchReplyBody.Groups["ReplyMessage"].Value;

                                List<string> MessageLines = CSH.StringWrapper(ReplyBody, 24);
                                string[] MessageArray = new string[MessageLines.Count];
                                int counter = 0;
                                foreach (string line in MessageLines)
                                {
                                    MessageArray[counter] = line;
                                    counter++;
                                }

                                ChucksMH.SendACARSViaAIRCOM(Tailnum, MessageArray);
                            }
                        }
                        else
                        {
                            EmailMessage message = EmailMessage.Bind(service, item.Id);
                            string NewFilename = ACARSWatcherPath + @"\" + DateTime.Now.ToString("ddMMyyyyHHmmssff") + "_Email.arq";
                            string AreqString = "<REPLYADDRESS>" + message.From.Address + "</REPLYADDRESS>" + Environment.NewLine +
                                "<AREQLINE>AREQ " + message.Subject.ToUpper() + "</AREQLINE>" + Environment.NewLine;

                            //Create File Drop
                            ChucksFH.WriteStringToFile(NewFilename, AreqString);
                        }

                    }
                    item.Delete(DeleteMode.MoveToDeletedItems);

                }
            }
            catch (Exception err)
            {
                LogEvent("EMAIL ERROR: " + err.ToString());
                Debug.WriteLine(err);
            }
        }
        public static void CheckAREQSubscriptions(object source, EventArgs e)
        {
            try
            {
                using (new Impersonator("APP_AREQ2", "jetblue", "HappyJetting!10"))
                {
                    using (ProdFltOpsDBDataContext db = new ProdFltOpsDBDataContext())
                    {
                        //Inactivate Expired Subs
                        var varExpired =
                            from expiredSubs in db.tblAreqSubscriptions
                            where ((expiredSubs.SubExpiriation < DateTime.Now) && (expiredSubs.SubActive == true))
                            select expiredSubs;

                        if (varExpired != null)
                        {
                            foreach (var expiredSub in varExpired)
                            {
                                expiredSub.SubActive = false;
                            }

                            db.SubmitChanges();
                        }

                        //Get Active Subs
                        var varSubs =
                            from foundSubs in db.tblAreqSubscriptions
                            where foundSubs.SubActive == true
                            select foundSubs;

                        if (varSubs != null)
                        {
                            foreach (var sub in varSubs)
                            {
                                switch (sub.AreqCommand)
                                {
                                    //case "RLS":
                                    //    string[] arrRLS_Req = Regex.Split(sub.CommandSent.Trim(), " ");

                                    //    if (arrRLS_Req.Length == 3) RequestDate = DateTime.Parse(arrRLS_Req[2]);
                                    //    int intFltNum = Int16.Parse(arrRLS_Req[1]);

    
                                    //    FltRlsWebSvc.FlightReleaseWebservice Svc = new FltRlsWebSvc.FlightReleaseWebservice();

                                    //    string[] release = Svc.GetFlightReleaseArray(FlightNumber, strDepCity);

                                    //    if (release.Length != 0)


                                    //    //If it is available drop an AREQ Request in XML format to the ACARSWatcherPath
                                    //    if (release.Length != 0)
                                    //    {
                                    //        //Release found.. Drop file
                                    //        string NewFilename = ACARSWatcherPath + @"\" + DateTime.Now.ToString("ddMMyyyyHHmmssff") + "_Email.arq";
                                    //        string AreqString = "<REPLYADDRESS>" + sub.SubAddress + "</REPLYADDRESS>" + Environment.NewLine +
                                    //            "<AREQLINE>AREQ " + sub.CommandSent + "</AREQLINE>" + Environment.NewLine;

                                    //        //Create File Drop
                                    //        ChucksFH.WriteStringToFile(NewFilename, AreqString);

                                    //        //Expire Subscription so that it will be deleted
                                    //        sub.SubActive = false;

                                    //        db.SubmitChanges();
                                    //    }
                                    //    else
                                    //        //No Release Found
                                    //        Debug.WriteLine("");
                                    //    break;
                                    case "STIMES":
                                        string[] arrSTIMES_Req = Regex.Split(sub.CommandSent.Trim(), " ");
                                        DateTime STIMES_RequestDate = DateTime.Parse(DateTime.Now.ToShortDateString());
                                        if (arrSTIMES_Req.Length == 3) STIMES_RequestDate = DateTime.Parse(arrSTIMES_Req[2]);
                                  

                                        DateTime dtReqBegin = new DateTime(STIMES_RequestDate.Year, STIMES_RequestDate.Month, STIMES_RequestDate.Day, 0, 0, 0, 0);
                                        DateTime dtReqEnd = new DateTime(STIMES_RequestDate.Year, STIMES_RequestDate.Month, STIMES_RequestDate.Day, 23, 59, 59, 0);

                                        ChucksClassLibrary.prodFlight_v3.FlightDetail[] FlightsResponse = ChucksWSH.prd_GetFlightsByFlightNumber_30("", arrSTIMES_Req[1], "", "", dtReqBegin, dtReqEnd);
                                        if ((FlightsResponse != null) && (FlightsResponse.Count() == 1))
                                        {
                                            ChucksStringHander CSH = new ChucksStringHander();
                                            string ETA_ETD_MD5 = CSH.CreateMD5Hash(FlightsResponse[0].CurrentDepartureDateTime.ToString() +
                                                FlightsResponse[0].CurrentArrivalDateTime.ToString());
                                            string DepDelay_ArrDelay_MD5 = CSH.CreateMD5Hash(FlightsResponse[0].DepartureDelayCode.ToString() + FlightsResponse[0].ArrivalDelayCode.ToString());

                                            if ((ETA_ETD_MD5 != sub.MD5Hash1) || (DepDelay_ArrDelay_MD5 != sub.MD5Hash2))
                                            {
                                                //New ETA or ETD Submit STIMES AGAIN with file drop
                                                string NewFilename = ACARSWatcherPath + @"\" + DateTime.Now.ToString("ddMMyyyyHHmmssff") + "_Email.arq";
                                                string AreqString = "<REPLYADDRESS>" + sub.SubAddress + "</REPLYADDRESS>" + Environment.NewLine +
                                                    "<AREQLINE>AREQ " + sub.CommandSent + "</AREQLINE>" + Environment.NewLine;

                                                //Create File Drop
                                                ChucksFH.WriteStringToFile(NewFilename, AreqString);

                                                //Expire Subscription so that it will be deleted
                                                sub.SubActive = false;
                                                db.SubmitChanges();
                                            }
                                        }

                                        break;

                                    case "FLTSUM":
                                    case "PREFLIGHT":
                                        string[] arrFLTSUM_Req = Regex.Split(sub.CommandSent.Trim(), " ");
                                        DateTime RequestDate = DateTime.Parse(DateTime.Now.ToShortDateString());
                                        if (arrFLTSUM_Req.Length == 3) RequestDate = DateTime.Parse(arrFLTSUM_Req[2]);
                                        int intFltNum = Int16.Parse(arrFLTSUM_Req[1]);

                                        ReleaseViewsDataContext ReleaseView = new ReleaseViewsDataContext();

                                        //Check to see if release is available
                                        var varRelease =
                                            from foundReleases in ReleaseView.vw_DispatchReleaseReportings
                                            where foundReleases.FltNo == intFltNum.ToString() &&
                                                    foundReleases.FlightDate == RequestDate
                                            orderby foundReleases.Version descending
                                            select foundReleases;

                                        //If it is available drop an AREQ Request in XML format to the ACARSWatcherPath
                                        if (varRelease.Count() > 0)
                                        {
                                            //Release found.. Drop file
                                            string NewFilename = ACARSWatcherPath + @"\" + DateTime.Now.ToString("ddMMyyyyHHmmssff") + "_Email.arq";
                                            string AreqString = "<REPLYADDRESS>" + sub.SubAddress + "</REPLYADDRESS>" + Environment.NewLine +
                                                "<AREQLINE>AREQ " + sub.CommandSent + "</AREQLINE>" + Environment.NewLine;
                                            
                                            //Create File Drop
                                            ChucksFH.WriteStringToFile(NewFilename, AreqString);

                                            //Expire Subscription so that it will be deleted
                                            sub.SubActive = false;

                                            db.SubmitChanges();
                                        }
                                        else
                                            //No Release Found
                                            Debug.WriteLine("");
                                        break;
                                    default:
                                        LogEvent("Case not found in Subs" + sub.AreqCommand);
                                        break;
                                }
                            }

                            db.SubmitChanges();
                        }

                        //Delete Inactive Subs
                        var varInactive =
                            from inactive in db.tblAreqSubscriptions
                            where inactive.SubActive == false
                            select inactive;

                        if (varInactive != null)
                        {
                            foreach (var inactiveSub in varInactive)
                            {
                                db.tblAreqSubscriptions.DeleteOnSubmit(inactiveSub);
                            }

                            db.SubmitChanges();
                        }
                    }
                }
            }
            catch(Exception err)
            {
                Debug.WriteLine("AREQ Subscriptions Error: " + err.ToString());
                LogEvent("AREQ Subscriptions ERROR: " + err.ToString());
            }
        }
#region AREQHandlers
        public static void ParseACMREQMessage(object stateObj)
        {
            ObjState StObj;
            StObj = (ObjState)stateObj;
            string msgFilename = StObj.Filename;
            string OutputFilePath = StObj.OutputFilename;

            string ACMTailNum = "";
            string ACMFlightNum = "";
            string CommandSent = "";
            try
          {
              ACMREQHandler Handler = new ACMREQHandler();

                string ACMFilename = System.IO.Path.GetFileName(msgFilename);
                Regex rgxACMREQ = new Regex(@"FI\s(?<IATA>[A-Z0-9]{2})(?<FlightNumber>\d{1,4})/AN\sN(?<AircraftNumber>\d{3})\w\w");
                Regex rgxEmailACMREQ = new Regex(@"<REPLYADDRESS>(?<ReplyAddress>.+)</REPLYADDRESS>\r\n<AREQLINE>(ACMREQ|AREQ)\s(?<Command>.+)</AREQLINE>", RegexOptions.Singleline);
                Regex rgxJetblueEmail = new Regex(@".+@JETBLUE.COM", RegexOptions.Singleline);

          
                ChucksFileHandler ReadWholeFile = new ChucksFileHandler();
                //FileReader ReadWholeFile = new FileReader();
                string WholeFile = ReadWholeFile.ReadFile(msgFilename);
                Match mtchEmail = rgxEmailACMREQ.Match(WholeFile.ToUpper());
# region Email Section
                if (mtchEmail.Success)
                {
                    //string DisplayName = mtchEmail.Groups["ReplyAddress"].ToString();
                    //string ReplyAddress = ChucksMH.GetEmailString(DisplayName).ToUpper();
                    string ReplyAddress = mtchEmail.Groups["ReplyAddress"].ToString();
                    Match mtchJetblue = rgxJetblueEmail.Match(ReplyAddress);
                    CommandSent = mtchEmail.Groups["Command"].ToString().ToUpper();
                    string[] arrEmailACM = Regex.Split(CommandSent, " ");

                    //Create Mail Message
                    System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();  //Create Mail Message Object
                    mail.To.Add(ReplyAddress);
                    mail.Subject = "AREQ " + CommandSent;  // put subject here	

                    if (mtchJetblue.Success == false)
                    {
                        mail.Subject = "AREQ request DENIED";
                        mail.Body += "AREQ requests can only be sent to jetblue.com email addresses." + "\n";
                        ChucksMH.SendMail(mail);
                        return;
                    }

                    switch (Regex.Match(arrEmailACM[0], @"^(\w+\b.*?){1}").ToString()) //This REGEX finds first word in a string
                    {
                        case "SYNTAX":
                        case "HELP":
                        case "COMMANDS":
                        case "COMMAND":
                            string[] arrMsgHELP = Handler.AddACARSHeader(msgGouge);

                            mail.Body += "AREQ email funtionality is here." + "\n";
                            mail.Body += "Send and email to: AREQ@jetblue.com" + "\n";
                            mail.Body += "Fill the subject line with your AREQ commands. The body of the email is ignored." + "\n\n";
                            mail.Body += "Example: " + "\n";
                            mail.Body += "TO: AREQ@jetblue.com " + "\n";
                            mail.Body += "SUBJ: AREQ TURNS JFK " + "\n\n";
                            mail.Body += "Below is a list of all the current AREQ commands. " + "\n";
                            mail.Body += "If you have any questions, suggestions, or feedback please send them to" + "\n";
                            mail.Body += "Chuck Cook at charles.cook@jetblue.com " + "\n\n";

                            Handler.AddMailBody(arrMsgHELP, mail);

                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlCOMMANDS").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "DBSTATS":
                            string[] arrDBSTATS_Req = Regex.Split(CommandSent.Trim(), " ");
                            string[] arrMsgDBSTATS = Handler.AddACARSHeader(ParseACM_DBSTATS_Req(ReplyAddress, CommandSent));
                            Handler.AddMailBody(arrMsgDBSTATS, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlDBSTATS").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "CRWBRIEF":
                            string[] arrCRWBRIEF_Req = Regex.Split(CommandSent.Trim(), " ");
                            // DateTime dtDUTYReq = DateTime.Now;
                            // if (arrDUTY_Req.Length >= 4) dtDUTYReq = DateTime.Parse(arrDUTY_Req[3]);
                            string[] arrMsgCRWBRIEF = Handler.AddACARSHeader(ParseACM_CRWBRIEF_Req(ReplyAddress, CommandSent));
                            Handler.AddMailBody(arrMsgCRWBRIEF, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlCRWBRIEF").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "DUTY":
                            string[] arrDUTY_Req = Regex.Split(CommandSent.Trim(), " ");
                           // DateTime dtDUTYReq = DateTime.Now;
                           // if (arrDUTY_Req.Length >= 4) dtDUTYReq = DateTime.Parse(arrDUTY_Req[3]);
                            string[] arrMsgDUTY = Handler.AddACARSHeader(ParseACM_DUTY_Req(arrDUTY_Req[1], ReplyAddress, CommandSent));
                            Handler.AddMailBody(arrMsgDUTY, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlDUTY").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "MOT":
                            string[] arrMOT_Req = Regex.Split(CommandSent.Trim(), " ");
                            DateTime dtMOTReq = DateTime.Now; string strDepCity;
                            if (arrMOT_Req.Length >= 4) dtMOTReq = DateTime.Parse(arrMOT_Req[3]);
                            if (arrMOT_Req.Length == 2) 
                                strDepCity = ""; 
                            else 
                                strDepCity = arrMOT_Req[2];
                            string[] arrMsgMOT = Handler.AddACARSHeader(ParseACM_MOT_Req(arrMOT_Req[1], strDepCity, dtMOTReq, ReplyAddress, CommandSent));
                            Handler.AddMailBody(arrMsgMOT, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlMOT").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "HOTEL":
                        case "HOTELS":
                            string[] arrHotel_Req = Regex.Split(CommandSent.Trim(), " ");
                            string[] arrMsgHotel = Handler.AddACARSHeader(ParseACM_Hotel_Req(arrHotel_Req[1], ReplyAddress, CommandSent));
                            Handler.AddMailBody(arrMsgHotel, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlHOTEL").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "JBFLIGHTS":
                        case "JBFLTS":
                            string FlightDate;
                            string[] arrJBFLIGHTS_Req = Regex.Split(CommandSent.Trim(), " ");
                            if (arrJBFLIGHTS_Req.Length < 3) FlightDate = ""; else FlightDate = arrJBFLIGHTS_Req[2];
                            string[] arrMsgJBFLIGHTS = Handler.AddACARSHeader(ParseACM_JBFLIGHTS_Req(arrJBFLIGHTS_Req[1], FlightDate, ACMTailNum, CommandSent));
                            Handler.AddMailBody(arrMsgJBFLIGHTS, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlJBFLIGHTS").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "PAIRING":
                            string[] arrPAIRING_Req = Regex.Split(CommandSent.Trim(), " ");
                            DateTime dtPAIRING_Req = DateTime.Parse(DateTime.Now.ToShortDateString());
                            if (arrPAIRING_Req.Length == 3) dtPAIRING_Req = DateTime.Parse(arrPAIRING_Req[2]);
                            string[] arrMsgPAIRING = Handler.AddACARSHeader(ParseACM_PAIRING_Req(arrPAIRING_Req[1], dtPAIRING_Req, ACMTailNum, CommandSent));
                            Handler.AddMailBody(arrMsgPAIRING, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlPAIRING").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "PIC":
                            string[] arrPic_Req = Regex.Split(CommandSent.Trim(), " ");
                            ChucksMH.SendMail(ParseACM_PIC_Req(arrPic_Req[1], ReplyAddress, CommandSent));
                            Counters.Where(p => p.CounterName == "emlPIC").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "RLS":
                        case "RELEASE":
                            string[] arrRLS_Req = Regex.Split(CommandSent.Trim(), " ");
                            //DateTime dtRLSReq = DateTime.Now;
                            //if (arrRLS_Req.Length >= 3) dtRLSReq = DateTime.Parse(arrRLS_Req[2]);
                            string[] arrMsgRLS = Handler.AddACARSHeader(ParseACM_RLS_Req(arrRLS_Req[1], arrRLS_Req[2], ReplyAddress, CommandSent));
                            Handler.AddMailBody(arrMsgRLS, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlRLS").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "SKED":
                            string[] arrSked_Req = Regex.Split(CommandSent.Trim(), " ");
                            string[] arrMsgSked = Handler.AddACARSHeader(ParseACM_Sked_Req(arrSked_Req[1], ReplyAddress, CommandSent));
                            Handler.AddMailBody(DoAddHTMLTags(arrMsgSked), mail);
                            mail.IsBodyHtml = true;
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlSKED").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "RAV":
                            string[] arrRAV_Req = Regex.Split(CommandSent.Trim(), " ");
                            DateTime dtRAV_Req = DateTime.Parse(DateTime.Now.ToShortDateString());
                            if (arrRAV_Req.Length == 3) dtRAV_Req = DateTime.Parse(arrRAV_Req[2]);
                            string[] arrMsgRAV = Handler.AddACARSHeader(ParseACM_RAV_Req(arrRAV_Req[1], dtRAV_Req, ReplyAddress, CommandSent));
                            Handler.AddMailBody(arrMsgRAV, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlRAV").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "SPOPENT":
                            string[] arrOpenT_Req = Regex.Split(CommandSent.Trim(), " ");
                            DateTime dtOPENT_Req = DateTime.Parse(DateTime.Now.ToShortDateString());
                            if (arrOpenT_Req.Length == 3) dtOPENT_Req = DateTime.Parse(arrOpenT_Req[2]);
                            string[] arrMsgOpenT = Handler.AddACARSHeader(ParseACM_OpenT_Req(arrOpenT_Req[1],dtOPENT_Req, ReplyAddress, CommandSent));
                            Handler.AddMailBody(arrMsgOpenT, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlOPENT").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "SEDCT":
                            string[] arrSEDCT_Req = Regex.Split(CommandSent.Trim(), " ");
                            string[] arrMsgSEDCT = Handler.AddACARSHeader(ParseACM_SEDCT_Req(arrSEDCT_Req, ReplyAddress, CommandSent));
                            Handler.AddMailBody(arrMsgSEDCT, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlSEDCT").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "EDCT":
                            string[] arrEDCT_Req = Regex.Split(CommandSent.Trim(), " ");
                            DateTime dtReq = DateTime.MinValue;
                            if (arrEDCT_Req.Length >= 3) dtReq = DateTime.Parse(arrEDCT_Req[2]);
                            string[] arrMsgEDCT = Handler.AddACARSHeader(ParseACM_TIMES_DELAY_Req(arrEDCT_Req[1], dtReq, ACMTailNum, "TIMES", CommandSent));
                            Handler.AddMailBody(arrMsgEDCT, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlEDCT").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "CODES":
                        case "DOORS":
                        case "DOOR":
                            string[] arrDoors_Req = Regex.Split(CommandSent.Trim(), " ");
                            string[] arrMsgDoors = Handler.AddACARSHeader(ParseACM_Doors_Req(arrDoors_Req[1], ReplyAddress, CommandSent));
                            Handler.AddMailBody(arrMsgDoors, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlDOORS").SingleOrDefault().CurrentCount += 1;
                            //cntDOORS += 1;
                            break;
                        //case "FLTSUM":
                        //case "FLIGHTSUM":
                        //    string[] arrFLTSUM_Req = Regex.Split(CommandSent.Trim(), " ");
                        //    DateTime dtFLTSUM_Req = DateTime.Parse(DateTime.Now.ToShortDateString());
                        //    if (arrFLTSUM_Req.Length == 3) dtFLTSUM_Req = DateTime.Parse(arrFLTSUM_Req[2]);
                        //    string[] arrMsgFLTSUM = Handler.AddACARSHeader(ParseACM_FLTSUM_Req(arrFLTSUM_Req[1], dtFLTSUM_Req, ReplyAddress, CommandSent));
                        //    //Add HTML tags and CR to email body
                        //    mail.IsBodyHtml = true;
                        //    Handler.AddMailBody(DoAddHTMLTags(arrMsgFLTSUM), mail);
                        //    ChucksMH.SendMail(mail);
                        //    Counters.Where(p => p.CounterName == "emlFLTSUM").SingleOrDefault().CurrentCount += 1;
                        //    //cntFLTSUM += 1;
                        //    break;
                        case "PROGRAMS":
                            string[] arrPROGRAMS_Req = Regex.Split(CommandSent.Trim(), " ");
                            string[] arrMsgPROGRAMS = Handler.AddACARSHeader(ParseACM_PROGRAMS_Req(arrPROGRAMS_Req[1], ACMTailNum, CommandSent));
                            Handler.AddMailBody(arrMsgPROGRAMS, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlPROGRAMS").SingleOrDefault().CurrentCount += 1;
                            //cntPROGRAMS += 1;
                            break;
                        case "TAXI":
                            string[] arrTAXI_Req = Regex.Split(CommandSent.Trim(), " ");
                            string[] arrMsgTAXI = Handler.AddACARSHeader(ParseACM_TAXI_Req(arrTAXI_Req[1], ACMTailNum, CommandSent));
                            Handler.AddMailBody(arrMsgTAXI, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlTAXI").SingleOrDefault().CurrentCount += 1;
                            //cntTAXI += 1;
                            break;
                        case "TURNS":
                            string TurnTime;
                            string[] arrTURNS_Req = Regex.Split(CommandSent.Trim(), " ");
                            if (arrTURNS_Req.Length < 3) TurnTime = ""; else TurnTime = arrTURNS_Req[2];
                            string[] arrMsgTurns = Handler.AddACARSHeader(ParseACM_TURNS_Req(arrTURNS_Req[1], TurnTime, ACMTailNum, CommandSent));
                            Handler.AddMailBody(arrMsgTurns, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlTURNS").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "TIMES":
                        case "STIMES":
                        case "DELAY":
                        case "DELAYCODE":
                            string[] arrTIMES_Req = Regex.Split(CommandSent.Trim(), " ");
                            DateTime dtReqTimes = DateTime.MinValue;
                            if (arrTIMES_Req.Length >= 3) dtReqTimes = DateTime.Parse(arrTIMES_Req[2]);
                            string[] arrMsgTimes = Handler.AddACARSHeader(ParseACM_TIMES_DELAY_Req(arrTIMES_Req[1], dtReqTimes, ReplyAddress, "TIMES", CommandSent));
                            Handler.AddMailBody(arrMsgTimes, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlTIMES").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "CREW":
                        case "SPCREW":
                        case "DISPCREW":
                            string[] arrCREW_Req = Regex.Split(CommandSent.Trim(), " ");
                            DateTime dtCrewReq = DateTime.Now;
                            if (arrCREW_Req.Length >= 3) dtCrewReq = DateTime.Parse(arrCREW_Req[2]);
                            string[] arrMsgCrew = Handler.AddACARSHeader(ParseACM_CREW_Req(arrCREW_Req[1], dtCrewReq, ReplyAddress, CommandSent));
                            mail.IsBodyHtml = true;
                            Handler.AddMailBody(DoAddHTMLTags(arrMsgCrew), mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlCREW").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "LOADS":
                        case "SPLOADS":
                            string[] arrLOADS_Req = Regex.Split(CommandSent.Trim(), " ");
                            DateTime dtLoadsReq = DateTime.Now;
                            if (arrLOADS_Req.Length >= 3) dtLoadsReq = DateTime.Parse(arrLOADS_Req[2]);
                            string[] arrMsgLoads = Handler.AddACARSHeader(ParseACM_LOADS_Req(arrLOADS_Req[1], dtLoadsReq, ReplyAddress , CommandSent));
                            Handler.AddMailBody(arrMsgLoads, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlLOADS").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "TAIL":
                            string[] arrTAIL_Req = Regex.Split(CommandSent.Trim(), " ");
                            DateTime dtTailReq = DateTime.Now;
                            if (arrTAIL_Req.Length >= 3) dtTailReq = DateTime.Parse(arrTAIL_Req[2]);
                            string[] arrMsgTail = Handler.AddACARSHeader(ParseACM_TAIL_Req(arrTAIL_Req[1], dtTailReq, ACMTailNum, CommandSent));
                            Handler.AddMailBody(arrMsgTail, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlTAIL").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "INBOUND":
                            string[] arrINBOUND_Req = Regex.Split(CommandSent.Trim(), " ");
                            DateTime dtInboundReq = DateTime.Now;
                            if (arrINBOUND_Req.Length >= 3) dtInboundReq = DateTime.Parse(arrINBOUND_Req[2]);
                            string[] arrMsgInbound = Handler.AddACARSHeader(ParseACM_INBOUND_Req(arrINBOUND_Req[1], dtInboundReq, ACMTailNum, CommandSent));
                            Handler.AddMailBody(arrMsgInbound, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlINBOUND").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "PREFLIGHT":
                        case "FLTSUM":
                        case "FLIGHTSUM":
                            string[] arrPREFLIGHT_Req = Regex.Split(CommandSent.Trim(), " ");
                            DateTime dtPREFLIGHTReq = DateTime.Parse(DateTime.Now.ToShortDateString());
                            if (arrPREFLIGHT_Req.Length >= 3) dtPREFLIGHTReq = DateTime.Parse(arrPREFLIGHT_Req[2]);
                            string[] arrMsgPREFLIGHT = CreatePREFLIGHT(arrPREFLIGHT_Req, dtPREFLIGHTReq, ReplyAddress, CommandSent);
                            //Add HTML tags and CR to email body
                            mail.IsBodyHtml = true;
                            Handler.AddMailBody(DoAddHTMLTags(arrMsgPREFLIGHT), mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlPREFLIGHT").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "DELAYS":
                            string[] arrEDCTDELAY_Req = Regex.Split(CommandSent.Trim(), " ");
                            string[] arrMsgEDCTDELAY = Handler.AddACARSHeader(ParseACM_EDCTDELAYS_Req(arrEDCTDELAY_Req[1], ACMTailNum, CommandSent));
                            Handler.AddMailBody(arrMsgEDCTDELAY, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlDELAYS").SingleOrDefault().CurrentCount += 1;
                            break;
                        case "BRIEF":
                            string[] arrBRIEF_Req = Regex.Split(CommandSent.Trim(), " ");
                            string[] arrMsgBRIEF = CreateBRIEF(arrBRIEF_Req, ACMTailNum, CommandSent);
                            Handler.AddMailBody(arrMsgBRIEF, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlBRIEF").SingleOrDefault().CurrentCount += 1;
                            //cntBRIEF += 1;
                            break;
                        case "SCORES":
                            string[] arrSCORES_Req = Regex.Split(CommandSent.Trim(), " ");
                            string[] arrMsgSCORES = Handler.AddACARSHeader(Scores(arrSCORES_Req, ACMTailNum, CommandSent));
                            Handler.AddMailBody(arrMsgSCORES, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlSCORES").SingleOrDefault().CurrentCount += 1;
                            //cntSCORES += 1;
                            break;
                        case "STOCK":
                            string[] arrSTOCK_Req = Regex.Split(CommandSent.Trim(), " ");
                            string[] arrMsgSTOCK = Handler.AddACARSHeader(Stock(arrSTOCK_Req, ACMTailNum, CommandSent));
                            Handler.AddMailBody(arrMsgSTOCK, mail);
                            ChucksMH.SendMail(mail);
                            Counters.Where(p => p.CounterName == "emlSTOCK").SingleOrDefault().CurrentCount += 1;
                            //cntSTOCK += 1;
                            break;
                        default:
                            string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                            string[] arrUnkERROR = Regex.Split(msgERROR, ",");
                            Handler.AddMailBody(arrUnkERROR, mail);
                            ChucksMH.SendMail(mail);
                            break;
                    }
                    AREQStatsEMAIL++;
                    return;
                }
#endregion
                StreamReader srACM = new StreamReader(msgFilename);
                srACM.ReadLine(); srACM.ReadLine(); srACM.ReadLine(); //Read the first three lines

                Match TailNumMATCH = rgxACMREQ.Match(srACM.ReadLine());// Match Line #4
                srACM.ReadLine();                                        //Read Line #5

                string TextMsg = srACM.ReadToEnd();
                TextMsg = Regex.Replace(TextMsg, @"[\n\r]", " ");
                string[] arrACM = Regex.Split(TextMsg, ","); //Read Line #6
                CommandSent = arrACM[2].ToString();
                if (TailNumMATCH.Success == true)
                {
                    ACMTailNum = TailNumMATCH.Groups["AircraftNumber"].ToString();
                    ACMFlightNum = TailNumMATCH.Groups["FlightNumber"].ToString();
                        
                    switch (Regex.Match(arrACM[2], @"^(\w+\b.*?){1}").ToString()) //This REGEX finds first word in a string
                        {
                            case "SYNTAX":
                            case "HELP":
                            case "COMMANDS":
                            case "COMMAND":
                               // string[] arrMsgHELP = SendACM_HELP(ACMTailNum, CommandSent);
                                string[] arrMsgHELP = Handler.AddACARSHeader(msgGouge);
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgHELP);
                                Counters.Where(p => p.CounterName == "COMMANDS").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "CRWBRIEF":
                                string[] arrCRWBRIEF_Req = Regex.Split(arrACM[2].Trim(), " ");
                                string[] arrMsgCRWBRIEF_ = Handler.AddACARSHeader(ParseACM_CRWBRIEF_Req(ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgCRWBRIEF_);
                                Counters.Where(p => p.CounterName == "CRWBRIEF").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "TWX":
                                string[] arrTWX_Req = Regex.Split(arrACM[2].Trim(), " ");
                                DateTime dtTWX_Req = DateTime.Parse(DateTime.Now.ToShortDateString());
                                if (arrTWX_Req.Length == 4) dtTWX_Req = DateTime.Parse(arrTWX_Req[3]);
                                string[] arrMsgTWX_ = Handler.AddACARSHeader(ParseACM_TWX_Req(arrTWX_Req[1], arrTWX_Req[2], ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgTWX_);
                                Counters.Where(p => p.CounterName == "TWX").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "DUTY":
                                string[] arrDUTY_Req = Regex.Split(arrACM[2].Trim(), " ");
                                //DateTime dtDUTY_Req = DateTime.Parse(DateTime.Now.ToShortDateString());
                                //if (arrDUTY_Req.Length == 3) dtDUTY_Req = DateTime.Parse(arrDUTY_Req[2]);
                                string[] arrMsgDUTY_ = Handler.AddACARSHeader(ParseACM_DUTY_Req(arrDUTY_Req[1], ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgDUTY_);
                                Counters.Where(p => p.CounterName == "DUTY").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "MOT":
                                string[] arrMOT_Req = Regex.Split(arrACM[2].Trim(), " ");
                                DateTime dtMOT_Req = DateTime.Parse(DateTime.Now.ToShortDateString());
                                string strDepCity;
                                if (arrMOT_Req.Length == 4) dtMOT_Req = DateTime.Parse(arrMOT_Req[3]);
                                if (arrMOT_Req.Length == 2)
                                    strDepCity = "";
                                else
                                    strDepCity = arrMOT_Req[2];
                                string[] arrMsgMOT_ = Handler.AddACARSHeader(ParseACM_MOT_Req(arrMOT_Req[1], strDepCity, dtMOT_Req, ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgMOT_);
                                Counters.Where(p => p.CounterName == "MOT").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "HOTEL":
                            case "HOTELS":
                                string[] arrHotel_Req = Regex.Split(arrACM[2].Trim(), " ");
                                string[] arrMsgHotel = Handler.AddACARSHeader(ParseACM_Hotel_Req(arrHotel_Req[1], ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgHotel);
                                Counters.Where(p => p.CounterName == "HOTEL").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "JBFLTS":
                            case "JBFLIGHTS":
                                string FlightDate;
                                string[] arrJBFLIGHTS_Req = Regex.Split(arrACM[2].Trim(), " ");
                                if (arrJBFLIGHTS_Req.Length < 3) FlightDate = ""; else FlightDate = arrJBFLIGHTS_Req[2];
                                string[] arrMsgJBFLIGHTS = Handler.AddACARSHeader(ParseACM_JBFLIGHTS_Req(arrJBFLIGHTS_Req[1], FlightDate, ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgJBFLIGHTS);
                                Counters.Where(p => p.CounterName == "JBFLIGHTS").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "PAIRING":
                                string[] arrPAIRING_Req = Regex.Split(arrACM[2].Trim(), " ");
                                DateTime dtPAIRING_Req = DateTime.Parse(DateTime.Now.ToShortDateString());
                                if (arrPAIRING_Req.Length == 3) dtPAIRING_Req = DateTime.Parse(arrPAIRING_Req[2]);
                                string[] arrMsgPAIRING_ = Handler.AddACARSHeader(ParseACM_PAIRING_Req(arrPAIRING_Req[1], dtPAIRING_Req, ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgPAIRING_);
                                Counters.Where(p => p.CounterName == "PAIRING").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "SKED":
                                string[] arrSked_Req = Regex.Split(arrACM[2].Trim(), " ");
                                string[] arrMsgSked = Handler.AddACARSHeader(ParseACM_Sked_Req(arrSked_Req[1], ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgSked);
                                Counters.Where(p => p.CounterName == "SKED").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "RAV":
                                string[] arrRAV_Req = Regex.Split(arrACM[2].Trim(), " ");
                                DateTime dtRAV_Req = DateTime.Parse(DateTime.Now.ToShortDateString());
                                if (arrRAV_Req.Length == 3) dtRAV_Req = DateTime.Parse(arrRAV_Req[2]);
                                string[] arrMsgRAV = Handler.AddACARSHeader(ParseACM_RAV_Req(arrRAV_Req[1], dtRAV_Req, ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgRAV);
                                Counters.Where(p => p.CounterName == "RAV").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "SPOPENT":
                                string[] arrOpenT_Req = Regex.Split(arrACM[2].Trim(), " ");
                                DateTime dtOPENT_Req = DateTime.Parse(DateTime.Now.ToShortDateString());
                                if (arrOpenT_Req.Length == 3) dtOPENT_Req = DateTime.Parse(arrOpenT_Req[2]);
                                string[] arrMsgOpenT = Handler.AddACARSHeader(ParseACM_OpenT_Req(arrOpenT_Req[1],dtOPENT_Req, ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgOpenT);
                                Counters.Where(p => p.CounterName == "OPENT").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "SEDCT":
                                string[] arrSEDCT_Req = Regex.Split(arrACM[2].Trim(), " ");
                                DateTime dtReqSEDCT = DateTime.MinValue;
                                string[] arrMsgSEDCT = Handler.AddACARSHeader(ParseACM_SEDCT_Req(arrSEDCT_Req, ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgSEDCT);
                                Counters.Where(p => p.CounterName == "SEDCT").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "EDCT":
                                string[] arrEDCT_Req = Regex.Split(arrACM[2].Trim(), " ");
                                DateTime dtReqEDCT = DateTime.MinValue;
                                if (arrEDCT_Req.Length >= 3) dtReqEDCT = DateTime.Parse(arrEDCT_Req[2]);
                                string[] arrMsgEDCT = Handler.AddACARSHeader(ParseACM_TIMES_DELAY_Req(arrEDCT_Req[1], dtReqEDCT, ACMTailNum, "TIMES", CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgEDCT);
                                Counters.Where(p => p.CounterName == "EDCT").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "CODES":
                            case "DOORS":
                            case "DOOR":
                                string[] arrDoors_Req = Regex.Split(arrACM[2].Trim(), " ");
                                string[] arrMsgDoors = Handler.AddACARSHeader(ParseACM_Doors_Req(arrDoors_Req[1], ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgDoors);
                                Counters.Where(p => p.CounterName == "DOORS").SingleOrDefault().CurrentCount += 1;
                                break;
                            //case "FLTSUM":
                            //case "FLIGHTSUM":
                            //    string[] arrFLTSUM_Req = Regex.Split(arrACM[2].Trim(), " ");
                            //    DateTime dtFLTSUM_Req = DateTime.Parse(DateTime.Now.ToShortDateString());
                            //    if (arrFLTSUM_Req.Length == 3) dtFLTSUM_Req = DateTime.Parse(arrFLTSUM_Req[2]);
                            //    string[] arrMsgFLTSUM_ = Handler.AddACARSHeader(ParseACM_FLTSUM_Req(arrFLTSUM_Req[1], dtFLTSUM_Req, ACMTailNum, CommandSent));
                            //    ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgFLTSUM_);
                            //    Counters.Where(p => p.CounterName == "FLTSUM").SingleOrDefault().CurrentCount += 1;
                            //    //cntFLTSUM += 1;
                            //    break;
                            case "TURNS":
                                string TurnTime;
                                string[] arrTURNS_Req = Regex.Split(arrACM[2].Trim(), " ");
                                if (arrTURNS_Req.Length < 3) TurnTime = ""; else TurnTime = arrTURNS_Req[2];
                                string[] arrMsgTurns = Handler.AddACARSHeader(ParseACM_TURNS_Req(arrTURNS_Req[1], TurnTime, ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgTurns);
                                Counters.Where(p => p.CounterName == "TURNS").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "TIMES":
                            case "DELAY":
                            case "DELAYCODE":
                                string[] arrTIMES_Req = Regex.Split(arrACM[2].Trim(), " ");
                                DateTime dtReq = DateTime.MinValue;
                                if (arrTIMES_Req.Length >= 3) dtReq = DateTime.Parse(arrTIMES_Req[2]);
                                string[] arrMsgTimes = Handler.AddACARSHeader(ParseACM_TIMES_DELAY_Req(arrTIMES_Req[1], dtReq, ACMTailNum, "TIMES", CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgTimes);
                                Counters.Where(p => p.CounterName == "TIMES").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "TAXI":
                                string[] arrTAXI_Req = Regex.Split(arrACM[2].Trim(), " ");
                                string[] arrMsgTAXI = Handler.AddACARSHeader(ParseACM_TAXI_Req(arrTAXI_Req[1], ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgTAXI);
                                Counters.Where(p => p.CounterName == "TAXI").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "CREW":
                            //case "SPCREW": //Disabled due to securty Restrictions from ACARS
                            case "DISPCREW":
                                string[] arrCREW_Req = Regex.Split(arrACM[2].Trim(), " ");
                                DateTime dtCrewReq = DateTime.Now;
                                if (arrCREW_Req.Length >= 3) dtCrewReq = DateTime.Parse(arrCREW_Req[2]);
                                string[] arrMsgCrew = Handler.AddACARSHeader(ParseACM_CREW_Req(arrCREW_Req[1], dtCrewReq, ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgCrew);
                                Counters.Where(p => p.CounterName == "CREW").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "LOADS":
                            case "SPLOADS":
                                string[] arrLOADS_Req = Regex.Split(arrACM[2].Trim(), " ");
                                DateTime dtLoadsReq = DateTime.Now;
                                if (arrLOADS_Req.Length >= 3) dtLoadsReq = DateTime.Parse(arrLOADS_Req[2]);
                                string[] arrMsgLoads = Handler.AddACARSHeader(ParseACM_LOADS_Req(arrLOADS_Req[1], dtLoadsReq, ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgLoads);
                                Counters.Where(p => p.CounterName == "LOADS").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "TAIL":
                                string[] arrTAIL_Req = Regex.Split(arrACM[2].Trim(), " ");
                                DateTime dtTailReq = DateTime.Now;
                                if (arrTAIL_Req.Length >= 3) dtTailReq = DateTime.Parse(arrTAIL_Req[2]);
                                string[] arrMsgTail = Handler.AddACARSHeader(ParseACM_TAIL_Req(arrTAIL_Req[1], dtTailReq, ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgTail);
                                Counters.Where(p => p.CounterName == "TAIL").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "INBOUND":
                                string[] arrINBOUND_Req = Regex.Split(arrACM[2].Trim(), " ");
                                DateTime dtInboundReq = DateTime.Now;
                                if (arrINBOUND_Req.Length >= 3) dtTailReq = DateTime.Parse(arrINBOUND_Req[2]);
                                string[] arrMsgInbound = Handler.AddACARSHeader(ParseACM_INBOUND_Req(arrINBOUND_Req[1], dtInboundReq, ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgInbound);
                                Counters.Where(p => p.CounterName == "INBOUND").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "PREFLIGHT":
                            case "FLTSUM":
                            case "FLIGHTSUM":
                                string[] arrPREFLIGHT_Req = Regex.Split(arrACM[2].Trim(), " ");
                                DateTime dtPREFLIGHTReq = DateTime.Parse(DateTime.Now.ToShortDateString());
                                if (arrPREFLIGHT_Req.Length >= 3) dtPREFLIGHTReq = DateTime.Parse(arrPREFLIGHT_Req[2]);
                                string[] arrMsgPREFLIGHT = CreatePREFLIGHT(arrPREFLIGHT_Req, dtPREFLIGHTReq, ACMTailNum, CommandSent);
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgPREFLIGHT);
                                Counters.Where(p => p.CounterName == "PREFLIGHT").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "DELAYS":
                                string[] arrEDCTDELAY_Req = Regex.Split(arrACM[2].Trim(), " ");
                                string[] arrMsgEDCTDELAY = Handler.AddACARSHeader(ParseACM_EDCTDELAYS_Req(arrEDCTDELAY_Req[1], ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgEDCTDELAY);
                                Counters.Where(p => p.CounterName == "DELAYS").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "PROGRAMS":
                                string[] arrPROGRAMS_Req = Regex.Split(arrACM[2].Trim(), " ");
                                string [] arrMsgPGMS = Handler.AddACARSHeader(ParseACM_PROGRAMS_Req(arrPROGRAMS_Req[1], ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgPGMS);
                                Counters.Where(p => p.CounterName == "PROGRAMS").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "EMAIL":
                                //Send to email address
                                string[] arrEMAIL_Req = Regex.Split(arrACM[2].Trim(), " ");
                                arrACM[0] = arrEMAIL_Req[0];
                                arrACM[1] = arrEMAIL_Req[1].Replace("at", "@");
                                ParseACM_EMAIL_TEXT(arrACM, ACMTailNum, ACMFlightNum, CommandSent);
                                Counters.Where(p => p.CounterName == "EMAIL").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "TEXT":
                            case "MEMO":
                                string[] arrTEXT_Req = Regex.Split(arrACM[2].Trim(), " ");
                                arrACM[0] = arrTEXT_Req[0];
                                ParseACM_EMAIL_TEXT(arrACM, ACMTailNum, ACMFlightNum, CommandSent);
                                Counters.Where(p => p.CounterName == "TEXT").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "ACARS":
                               // string[] arrACARS_Req = Regex.Split(arrACM[2], " ");
                               // ParseACM_ACARS_Req(arrACM, arrACARS_Req[1], ACMTailNum);
                                break;
                            case "BRIEF":
                                string[] arrBRIEF_Req = Regex.Split(CommandSent.Trim(), " ");
                                string[] arrMsgBRIEF = CreateBRIEF(arrBRIEF_Req, ACMTailNum, CommandSent);
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgBRIEF);
                                Counters.Where(p => p.CounterName == "BRIEF").SingleOrDefault().CurrentCount += 1;
                                //cntBRIEF +=1;
                                break;
                            case "SCORES":
                                string[] arrSCORES_Req = Regex.Split(CommandSent.Trim(), " ");
                                string[] arrMsgSCORES = Handler.AddACARSHeader(Scores(arrSCORES_Req, ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgSCORES);
                                Counters.Where(p => p.CounterName == "SCORES").SingleOrDefault().CurrentCount += 1;
                                break;
                            case "STOCK":
                                string[] arrSTOCK_Req = Regex.Split(CommandSent.Trim(), " ");
                                string[] arrMsgSTOCK = Handler.AddACARSHeader(Stock(arrSTOCK_Req, ACMTailNum, CommandSent));
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgSTOCK);
                                Counters.Where(p => p.CounterName == "STOCK").SingleOrDefault().CurrentCount += 1;
                                break;
                            default:
                                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                                string[] arrUnkERROR = Regex.Split(msgERROR, ",");
                                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrUnkERROR);
                                break;
                        }
                }
                AREQStatsACARS++;
                srACM.Close();
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ Main Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ Main Sub, You Sent: " + CommandSent + " ERROR: " + err.StackTrace.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                string[] arrUnkERROR = Regex.Split(msgERROR, ",");
                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrUnkERROR);
            }
        }
        public static string ParseACM_DBSTATS_Req(string ACMTailNum, string CommandSent)
        {
            try
            {
                string msgDBSTATS = "";

                Prod_Fuller_CrewRegInfo.CrewRegInfo FullerSvc = new Prod_Fuller_CrewRegInfo.CrewRegInfo();

                string DBSTATSResp = FullerSvc.DBStatReport();

                if (DBSTATSResp == null)
                {
                    msgDBSTATS += "No DBStats data returned" + ",";
                }
                else
                {
                    DBSTATSResp = Regex.Replace(DBSTATSResp, @"\n", ",");
                    msgDBSTATS += DBSTATSResp;

                    Debug.WriteLine("");
                }

                return msgDBSTATS;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ DBSTATS Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ DBSTATS Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_CRWBRIEF_Req(string ACMTailNum, string CommandSent)
        {
            try
            {
                string msgCRWBRIEF = "";

                Prod_Fuller_CrewRegInfo.CrewRegInfo CrwBriefSvc = new Prod_Fuller_CrewRegInfo.CrewRegInfo();

                string CRWBRIEFResp = CrwBriefSvc.getCrewBriefing();

                if (CRWBRIEFResp == null)
                {
                    msgCRWBRIEF += "No CrwBrief data returned" + ",";
                }
                else
                {
                    CRWBRIEFResp = Regex.Replace(CRWBRIEFResp, @"\n", ",");
                    msgCRWBRIEF += CRWBRIEFResp;

                    Debug.WriteLine("");
                }

                return msgCRWBRIEF;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ CRWBRIEF Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ CREWBRIEF Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_TWX_Req(string strWeatherType, string strWeatherCity, string ACMTailNum, string CommandSent)
        {
            try
            {
                ChucksWeatherHandler CWXH = new ChucksWeatherHandler();

                string msgTWX = "";

                switch (strWeatherType)
                {
                    case "1":
                        //METAR ONLY
                        nsMETAR.METAR[] DepMETAR = null;
                        if (strWeatherCity.Length == 3)
                            DepMETAR = CWXH.GetMETAR_IATA(strWeatherCity);
                        else if (strWeatherCity.Length == 4)
                            DepMETAR = CWXH.GetMETAR_ICAO(strWeatherCity);

                        msgTWX += ",,CURRENT WX:";
                        if (DepMETAR != null) msgTWX += ",METAR: " + DepMETAR[0].raw_text;

                        break;
                    case "2":
                        //TAF ONLY
                        nsTAF.TAF[] DepTAF = null;
                        if (strWeatherCity.Length == 3)
                            DepTAF = CWXH.GetTAF_IATA(strWeatherCity);
                        else if (strWeatherCity.Length == 4)
                            DepTAF = CWXH.GetTAF_ICAO(strWeatherCity);

                        msgTWX += ",,FORECAST WX:";
                        if (DepTAF != null) msgTWX += ",TAF: " + DepTAF[0].raw_text;
                        break;
                    
                    case "3":
                        try
                        {
                            //METAR AND TAF
                            nsMETAR.METAR[] DepMETARTAF = null;
                            if (strWeatherCity.Length == 3)
                                DepMETARTAF = CWXH.GetMETAR_IATA(strWeatherCity);
                            else if (strWeatherCity.Length == 4)
                                DepMETARTAF = CWXH.GetMETAR_ICAO(strWeatherCity);
                            nsTAF.TAF[] DepTAFMETAR = null;
                            if (strWeatherCity.Length == 3)
                                DepTAFMETAR = CWXH.GetTAF_IATA(strWeatherCity);
                            else if (strWeatherCity.Length == 4)
                                DepTAFMETAR = CWXH.GetTAF_ICAO(strWeatherCity);

                            msgTWX += ",,CURRENT WX:";
                            if (DepMETARTAF != null) msgTWX += ",METAR: " + DepMETARTAF[0].raw_text;
                            msgTWX += ",,FORECAST WX:";
                            if (DepTAFMETAR != null) msgTWX += ",TAF: " + DepTAFMETAR[0].raw_text;
                        }
                        catch
                        {
                            msgTWX += "Error getting TAF/METAR Data,";
                        }
                        break;
                    default:

                        break;
                }

                return msgTWX;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ TWX Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ TWX Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_DUTY_Req(string strCrewID, string ACMTailNum, string CommandSent)
        {
            try
            {
                string msgDUTY = "CrewID: " + strCrewID + ",";
                DateTime dtReq = DateTime.UtcNow + new TimeSpan(0,5,0);
                int intCrewID;
                bool success = int.TryParse(strCrewID, out intCrewID);


                Prod_Fuller_CrewRegInfo.CrewRegInfo DutySvc = new Prod_Fuller_CrewRegInfo.CrewRegInfo();

                string DUTYResp = DutySvc.getCrewLegal(intCrewID, dtReq);

                if (DUTYResp == null)
                {
                    msgDUTY += "No Duty Times Found for " + strCrewID + ", on " + dtReq.ToShortDateString() + ",";
                }
                else
                {
                    BidQualWebservice.BidQualWebService BQWS = new BidQualWebservice.BidQualWebService();
                    BidQualWebservice.BidQualCrewData CrewData = BQWS.GetBidQualData(intCrewID);
                    msgDUTY += "CrewMember: " + CrewData.Equipment + " " + CrewData.Position + " " + CrewData.FirstName + " " + CrewData.LastName + ",,";

                    DUTYResp = Regex.Replace(DUTYResp, @"\n", ",");
                    msgDUTY += DUTYResp;
                   
                    Debug.WriteLine("");
                }

                return msgDUTY;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ DUTY Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ DUTY Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_MOT_Req(string FltNum, string DepCity, DateTime MOTDate, string ACMTailNum, string CommandSent)
        {
            try
            {
                string msgMOT = "Flight Number: " + FltNum + ",";
                DateTime dtReq = DateTime.MinValue;


                Prod_Fuller_CrewRegInfo.CrewRegInfo MOTSvc = new Prod_Fuller_CrewRegInfo.CrewRegInfo();

                string MOTResp = MOTSvc.getMOT(MOTDate, FltNum, DepCity);

                if (MOTResp == null)
                {
                    msgMOT += "No MOTs Found for " + FltNum + ", on " + dtReq.ToShortDateString() + ",";
                }
                else
                {
                    string strCrewID = Regex.Match(MOTResp, @"(?<=CrewID:\s).+").ToString();

                    MOTResp = Regex.Replace(MOTResp, @"\n", ",");
                    msgMOT += MOTResp;

                    int intCrewID;
                    bool success = int.TryParse(strCrewID, out intCrewID);
                    if (success)
                    {
                        BidQualWebservice.BidQualWebService BQWS = new BidQualWebservice.BidQualWebService();
                        BidQualWebservice.BidQualCrewData CrewData = BQWS.GetBidQualData(intCrewID);
                       // ChucksClassLibrary.prodCrew_v3.Crewmember Crew = ChucksWSH.GetCrewMember_30(intCrewID);
                        msgMOT += "CrewMember: " + CrewData.Equipment + " " + CrewData.Position + " " + CrewData.FirstName + " " + CrewData.LastName + ",,";
                        Debug.WriteLine("");
                    }

                    Debug.WriteLine(""); 
                }

                return msgMOT;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ MOT Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ MOT Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_Hotel_Req(string arrACM, string ACMTailNum, string CommandSent)
        {
            try
            {
                string msgHotel = "";
                string HotelCity = arrACM;
                clsSharePointHotels clsSPHotels = new clsSharePointHotels();
                List<clsSharePointHotels.Hotel> lstHotels = clsSPHotels.getAllHotelData();

                var varHotels =
                    from foundHotels in lstHotels
                    where foundHotels.IATACity == HotelCity
                    select foundHotels;

                if (varHotels.Count() > 0)
                {
                    foreach (var hotel in varHotels)
                    {
                        // Setup ACARS Message
                        msgHotel += ",,Hotel City: " + hotel.City +
                                    ",Hotel Name: " + hotel.HotelName +
                                    ",Address: " + hotel.Street + " " + hotel.City + " " + hotel.State + " " + hotel.Zip +
                                    ",Phone: " + hotel.Phone +
                                    ",Ground Transport: " + hotel.GroundTransport +
                                    ",Pickup Location: " + hotel.PickupLocation +
                                    ",TimeSpecial: " + hotel.TimeSpecial +
                                    ",Discount: " + hotel.Discount;
                    }
                }
                else
                    msgHotel += ",,NO HOTEL's FOUND for:  " + HotelCity;

                System.Diagnostics.Debug.Write("");
                return msgHotel;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ HOTEL Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ HOTEL Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_JBFLIGHTS_Req(string CityPair, string FlightDate, string ReplyAddress, string CommandSent)
        {
            DateTime StartTime = DateTime.MinValue;
            DateTime EndTime = DateTime.MinValue;
            string Departure;
            string Arrival;
            try
            {
                //TimeSpan LocalVariance = ChucksWSH.GetVariance(INRAirport);
                //DateTime LocalTimeNow = DateTime.UtcNow + LocalVariance;
                ChucksConvertTime CCT = new ChucksConvertTime();
                ChucksStringHander CSH = new ChucksStringHander();

                //Parse Flight Date
                if (FlightDate == "")
                {
                    StartTime = CCT.GetBeginningOfDay(DateTime.Now);
                    EndTime = CCT.GetEndOfDay(DateTime.Now);
                }
                else
                {
                    bool tryParseFlightDate = DateTime.TryParse(FlightDate, out StartTime);
                    if (tryParseFlightDate)
                    {
                        StartTime = CCT.GetBeginningOfDay(StartTime);
                        EndTime = CCT.GetEndOfDay(StartTime);
                    }
                }
                string msgJBFLIGHTS = "CityPair: " + CityPair + " " + StartTime.ToString("MM/dd/yy") + ",";

                //Parse CityPair

                if (CityPair.Length == 6)
                {
                    Departure = CSH.Left(CityPair, 3);
                    Arrival = CSH.Right(CityPair, 3);
                }
                else
                {
                    //Return Error invalid citypair
                    msgJBFLIGHTS += ", Invalid City Pair: " + CityPair +
                                    ",Example: AREQ JBFLTS JFKJAX";
                    return msgJBFLIGHTS;
                }

                ChucksClassLibrary.prodFlight_v3.FlightDetail[] FlightsResponse = ChucksWSH.prd_GetFlights_30(StartTime, EndTime, Departure, Arrival);
                if (FlightsResponse != null)
                {
                    string DepartureTime = "";

                    msgJBFLIGHTS += ",Flights FROM: " + Departure  + " - " + Arrival + ",";
                   // msgJBFLIGHTS += ",FLT    STATUS  (S)ETD   GATE   LOAD   EQUIP,";
                    for (int x = 0; x < FlightsResponse.Length; x++)
                    {
                        string strLoads = "";  string Status;
                        if (FlightsResponse[x].FlightStatus.ToString() == "CANCELLED")
                        {
                            Status = "CANCELD";
                        }
                        else if (FlightsResponse[x].FlightStatus.ToString() == "BOARDING")
                        {
                            Status = "BOARDNG";
                        }
                        else if (FlightsResponse[x].FlightStatus.ToString() == "DEPARTED")
                        {
                            Status = "DEPARTD";
                        }
                        else
                        {
                            Status = FlightsResponse[x].FlightStatus;
                        }

                        if (FlightsResponse[x].CurrentDepartureDateTime != FlightsResponse[x].ScheduledDepartureDateTime)
                            DepartureTime = "E" + FlightsResponse[x].CurrentDepartureDateTime.ToString("HHmm");
                        else
                            DepartureTime = "S" + FlightsResponse[x].ScheduledDepartureDateTime.ToString("HHmm");


                        //Get Loads
                        ChucksClassLibrary.prodFlight_v3.PassengerDetail[] LoadsResponse = ChucksWSH.prd_GetPaxDetails_30("B6", FlightsResponse[x].DepartureAirport, FlightsResponse[x].ArrivalAirport, FlightsResponse[x].FlightNumber, FlightsResponse[x].FlightDate);
                        if (LoadsResponse != null)
                        {
                            for (int i = 0; i < LoadsResponse.Length; i++)
                            {
                                if (LoadsResponse[i].PassengerGroup == "booked_pax")
                                {
                                    strLoads += "LD:" + LoadsResponse[i].PassengerCount + "/";
                                }
                                else if (LoadsResponse[i].PassengerGroup == "booked_pad")
                                {
                                    strLoads += LoadsResponse[i].PassengerCount;
                                }
                            }
                        }
                        //Convert 320 Equip Code
                        string Equip = "";
                        if (FlightsResponse[x].Equipment.ToString().Substring(0, 1) == "3")
                            Equip = "320";
                        else
                            Equip = "E90";

                        msgJBFLIGHTS +=
                            "F:" + FlightsResponse[x].FlightNumber + " " + Status.PadRight(7, ' ') + " " + DepartureTime + " G:" + FlightsResponse[x].DepartureGate + " " + strLoads + " " + Equip + ",";
                    }
                }
                else
                {
                    msgJBFLIGHTS += "No Flights Found for " + CityPair + ",between " + StartTime.ToShortTimeString() + "-" + EndTime.ToShortTimeString() + ",";
                }


                return msgJBFLIGHTS;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ JBFLIGHTS Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ JBFLIGHTS Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," 
                                + "Example: AREQ JBFLTS JFKJAX <optional mm/dd/yy>,"
                                + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_PAIRING_Req(string strPairing, DateTime PairingDate, string ReplyAddress, string CommandSent)
        {
            try
            {
                string msgPairing = "";


                ChucksClassLibrary.prodCrew_v3.PairingFlight[] response = ChucksWSH.GetPairingFlights_30(strPairing,PairingDate);
                ChucksClassLibrary.prodCrew_v3.PairingDutyPeriod[] DutyPeriodResponse = ChucksWSH.GetPairingDutyPeriods_30(strPairing, PairingDate);

                if (response != null)
                {
                    msgPairing += "PAIRING: " + PairingDate.ToShortDateString() + " " + strPairing + ",";
                    foreach (var leg in response)
                    {
                        // Setup ACARS Message
                        string DepartureTime; string ArrivalTime; string IsDeadHead;
                        if ( leg.ActualDepartureTime == null )
                            DepartureTime = "(S)" + leg.ScheduledDepartureTime.ToString("HHmm") + "L";
                        else
                            DepartureTime = "(A)" + leg.ActualDepartureTime.Value.ToString("HHmm") + "L";

                        if ( leg.ActualArrivalTime == null)
                            ArrivalTime = "(S)" + leg.ScheduledArrivalTime.ToString("HHmm") + "L";
                        else
                            ArrivalTime = "(A)" + leg.ActualArrivalTime.Value.ToString("HHmm") + "L";

                        if (leg.IsDeadhead) IsDeadHead = "DH";
                        else IsDeadHead = "  ";


                        msgPairing += "," + leg.FlightDate.ToString("ddd dd") +
                            " " + IsDeadHead + leg.FlightNumber.Trim() +
                            " " + leg.DepartureAirport + "-" + leg.ArrivalAirport +
                            " " + DepartureTime +
                            " " + ArrivalTime;

                        Debug.Write(" ");

                    }
                    if ((DutyPeriodResponse != null) && (DutyPeriodResponse.Count() > 1))
                    { 
                        msgPairing += ",,HOTEL INFO: ";
                        foreach (var dutyperiod in DutyPeriodResponse)
                        {
                            if (dutyperiod.HotelName != "")
                            {
                                var FindCity = (from leg in response
                                                where leg.LegNumber == dutyperiod.LegNumber - 5
                                                select leg).FirstOrDefault();

                                msgPairing += "," + FindCity.FlightDate.ToString("ddd dd") +
                                    " - " + FindCity.ArrivalAirport +
                                    " - " + dutyperiod.HotelName +
                                    " (" + dutyperiod.HotelPhoneNumber + ")";
                            }
                        }
                    }
                    msgPairing += ",,";
                }
                else // response to pairings was null
                    msgPairing += ",,NO PAIRING INFO FOUND FOR: " + PairingDate.ToShortDateString() + " " + strPairing;

                return msgPairing;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ PAIRING Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ PAIRING Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + 
                                  ",Example: AREQ PAIRING J2001A 7/11/12" + 
                                  msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_RLS_Req(string strFltNumber, string strDepCity, string ReplyAddress, string CommandSent)
        {
            try
            {
                string msgRLS = "Flt: " + strFltNumber + ",";

                int FlightNumber;
                bool success = int.TryParse(strFltNumber, out FlightNumber);
                if (success)
                {
                    FltRlsWebSvc.FlightReleaseWebservice Svc = new FltRlsWebSvc.FlightReleaseWebservice();

                    string[] release = Svc.GetFlightReleaseArray(FlightNumber, strDepCity);

                    if (release.Length != 0)
                    {
                        foreach (string line in release)
                        {
                            msgRLS += line + ",";
                        }
                    }
                    else // no release found
                    {
                        //Check for subscription
                        string Command = Regex.Match(CommandSent, @"^(\w+\b.*?){1}").ToString();
                        msgRLS = "No release info found for Flt: " + strFltNumber +
                                        ",,the release will be automatically delivered,to this email address if it becomes available,in the next two hours.,";

                        //Create Subscription
                        tblAreqSubscription newsub = new tblAreqSubscription();

                        newsub.CommandSent = CommandSent;
                        newsub.AreqCommand = Command;
                        newsub.SubActive = true;
                        newsub.SubAddress = ReplyAddress;
                        newsub.SubExpiriation = DateTime.Now + new TimeSpan(0, 120, 0);
                        newsub.SubStartTime = DateTime.Now;
                        newsub.SubType = "EMAIL";

                        using (new Impersonator("APP_AREQ2", "jetblue", "HappyJetting!10"))
                        {
                            using (ProdFltOpsDBDataContext db = new ProdFltOpsDBDataContext())
                            {
                                db.tblAreqSubscriptions.InsertOnSubmit(newsub);
                                db.SubmitChanges();
                            }
                        }
                    }
                }
                return msgRLS;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ RLS Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ RLS Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static MailMessage ParseACM_PIC_Req(string strEmpID, string ReplyAddress, string CommandSent)
        {
            try
            {
                    MailMessage mail = new MailMessage();
                    mail.To.Add(ReplyAddress);
                    mail.Subject = "AREQ PIC " + strEmpID;
                    string MailBody = "";
                    

                    int EmpID;
                    System.Drawing.Image CrewImage;
                    MemoryStream stream = new MemoryStream();
                    if (int.TryParse(strEmpID, out EmpID))
                    {
                        ChucksPhotoHandler CPH = new ChucksPhotoHandler();
                        CrewImage = CPH.getPhoto(EmpID);
                        CrewImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        stream.Seek(0, SeekOrigin.Begin);

                        BidQualWebservice.BidQualWebService BQWS = new BidQualWebservice.BidQualWebService();
                        BidQualWebservice.BidQualCrewData CrewData = BQWS.GetBidQualData(EmpID);
                        MailBody += "<p>"+ CrewData.Equipment + " " + CrewData.Position + " " + CrewData.FirstName + " " + CrewData.LastName + "</p><br>";
                        MailBody += "<p>This AREQ response came from an application managed by Chuck Cook in Flight Operations.</p>";
                    }

                    // PLAIN VIEW
                    string vwPlain = "This AREQ Crew Image must be viewed in HTML format." + Environment.NewLine;
                    AlternateView plainView = AlternateView.CreateAlternateViewFromString(vwPlain, null, "text/plain");

                    // HTML VIEW
                    // =====================================================================
                    // Fill the linked resource

                    LinkedResource data = new LinkedResource(stream, "image/jpeg");
                    string generatedName = strEmpID + "_image.jpg";

                    data.ContentType.MediaType = System.Net.Mime.MediaTypeNames.Image.Jpeg;

                    // Generate the linked resource for the image being embedded
                    string generatedSrc = "cid:" + generatedName;

                    data.ContentType.Name = generatedName;
                    data.ContentId = generatedName;

                    AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<img src='" + generatedSrc + "' />" + MailBody, null, "text/html");

                    htmlView.LinkedResources.Add(data);

                    mail.AlternateViews.Add(htmlView);
                    mail.AlternateViews.Add(plainView);

                    mail.IsBodyHtml = true;
                    mail.BodyEncoding = System.Text.Encoding.UTF8;

                    return mail;
            }

            catch (Exception err)
            {
                Debug.WriteLine("AREQ PIC Sub, You Sent: " + CommandSent + " Error: " + err.ToString());
                LogEvent("AREQ PIC Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                return null;
            }
        }
        public static string ParseACM_Sked_Req(string strEmpIDPIN, string ReplyAddress, string CommandSent)
        {
            try
            {
                Regex rgxJetblueEmail = new Regex(@".+@JETBLUE.COM", RegexOptions.Singleline);
                Match IsEmail = rgxJetblueEmail.Match(ReplyAddress.ToUpper());


                string msgSked = "";
                int intEmpID = int.Parse(strEmpIDPIN.Substring(0, strEmpIDPIN.Length - 4));


                ChucksWebServiceHandler CWH = new ChucksWebServiceHandler();
                string BirthCode = "";
                if (strEmpIDPIN.Length > 4)
                    BirthCode = strEmpIDPIN.Substring(strEmpIDPIN.Length - 4, 4);
                bool ValidEmpID = CWH.ValidateCrewmemberBirthdate(intEmpID, BirthCode);

                if (ValidEmpID)
                {

                    DateTime StartDate = DateTime.Now + new TimeSpan(-15, 0, 0, 0);
                    DateTime EndDate = DateTime.Now + new TimeSpan(15, 0, 0, 0);

                    ChucksClassLibrary.prodCrew_v3.Pairing[] response = ChucksWSH.GetCrewMemberSchedule_30(intEmpID, StartDate, EndDate);

                    if (response != null)
                    {
                        var SortedPairings = from pairings in response
                                             orderby pairings.StartDateTime
                                             select pairings;

                        msgSked += "Schedule for: " + intEmpID.ToString() + ",";
                        foreach (var pairing in SortedPairings)
                        {
                            // Setup ACARS Message
                            if (pairing.PairingKey != null)
                            {
                                if (IsEmail.Success)
                                {
                                    msgSked += ",<a href=\"mailto:AREQ@jetblue.com?subject=AREQ PAIRING " + pairing.PairingKey.PairingNumber + " " + pairing.StartDateTime.ToString("M/d/yy") + "\">" + pairing.PairingKey.PairingNumber + "</a> " + pairing.StartDateTime.ToString("M/d/yy HH:mm");
                                }
                                else
                                    msgSked += "," + pairing.PairingKey.PairingNumber + " " + pairing.StartDateTime.ToString("M/d/yy HH:mm");
                            }
                            else
                                msgSked += "," + pairing.TypeCode + " " + pairing.StartDateTime.ToString("M/d/yy HH:mm");

                            // Debug.Write(" ");

                        }
                        Debug.Write(" ");
                        msgSked += ",,";
                    }
                    else
                        msgSked += ",,NO SKED FOUND FOR EMPID: " + strEmpIDPIN;
                }
                else
                    msgSked += ",,INVALID PIN NUMBER: " + strEmpIDPIN;

                return msgSked;
            }

            catch (Exception err)
            {
                Debug.WriteLine("AREQ SKED Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ SKED Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_OpenT_Req(string BPECode, DateTime OpenTimeDate, string ACMTailNum, string CommandSent)
        {
            try
            {
                string msgOpenT = "";
                string Base = ""; string Position = ""; string Equipment = "";
                List<string> FAPositions = new List<string>(new string[] {"F1", "F2", "F3"});
                
               if (BPECode != "")
               {
                   switch (BPECode.Substring(0,1).ToUpper())
                   {
                       case "J":
                           Base = "JFK";
                           break;
                       case "B":
                           Base = "BOS";
                           break;
                       case "M":
                           Base = "MCO";
                           break;
                       case "F":
                           Base = "FLL";
                           break;
                       case "L":
                           Base = "LGB";
                           break;
                        default:
                            Debug.WriteLine("");
                            break;
                   }
                   switch (BPECode.Substring(1, 1).ToUpper())
                   {
                       case "2":
                           Equipment = "A320";
                           break;
                       case "5":
                           Equipment = "E190";
                           break;
                       default:
                           Equipment = "";
                           Debug.WriteLine("");
                           break;
                   }
                   switch (BPECode.Substring(2, 1).ToUpper())
                   {
                       case "C":
                           Position = "CA";
                           break;
                       case "F":
                           Position = "FO";
                           break;
                       case "A":
                           Position = "FA";
                           break;
                       default:
                           Debug.WriteLine("");
                           break;
                   }
               }
               if (Position != "FA")
               {
                   ChucksClassLibrary.prodCrew_v3.OpenTimeDetail[] response = ChucksWSH.GetOpenTimeDetail_30(OpenTimeDate, Base, Position, Equipment);

                   if (response != null)
                   {
                       msgOpenT += "OPEN TIME for: " + OpenTimeDate.ToShortDateString() + " " + Base + " " + Equipment + " " + Position + ",";
                       foreach (var pairing in response)
                       {
                           // Setup ACARS Message
                           msgOpenT += "," + pairing.PairingKey.PairingNumber + " " + pairing.PairingKey.Date.ToShortDateString();
                           Debug.Write(" ");

                       }
                       Debug.Write(" ");
                       msgOpenT += ",,";
                   }
                   else
                       msgOpenT += ",,NO OPEN TIME FOUND FOR " + Base + " " + Equipment + " " + Position + ",";
               }
               else
               {
                   foreach (var FAPos in FAPositions)
                   {
                       ChucksClassLibrary.prodCrew_v3.OpenTimeDetail[] response = ChucksWSH.GetOpenTimeDetail_30(OpenTimeDate, Base, FAPos, Equipment);

                       if (response != null)
                       {
                           msgOpenT += "OPEN TIME for: " + OpenTimeDate.ToShortDateString() + " " +  Base + " " + Equipment + " " + FAPos;
                           foreach (var pairing in response)
                           {
                               // Setup ACARS Message
                               msgOpenT += "," + pairing.PairingKey.PairingNumber + " " + pairing.PairingKey.Date.ToShortDateString();
                               Debug.Write(" ");

                           }
                           Debug.Write(" ");
                           msgOpenT += ",,";
                       }
                       else
                           msgOpenT += ",,NO OPEN TIME FOUND FOR " + Base + " " + Equipment + " " + FAPos + ",";
                   }
               }

                return msgOpenT;
            }

            catch (Exception err)
            {
                Debug.WriteLine("AREQ OPENT Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ OPENT Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_RAV_Req(string BPECode, DateTime RAVDate, string ACMTailNum, string CommandSent)
        {
            try
            {
                string msgRAV = "";
                string Base = ""; string Position = ""; string Equipment = "";
                List<string> FAPositions = new List<string>(new string[] { "F1", "F2", "F3" });

                if (BPECode != "")
                {
                    switch (BPECode.Substring(0, 1).ToUpper())
                    {
                        case "J":
                            Base = "JFK";
                            break;
                        case "B":
                            Base = "BOS";
                            break;
                        case "M":
                            Base = "MCO";
                            break;
                        case "F":
                            Base = "FLL";
                            break;
                        case "L":
                            Base = "LGB";
                            break;
                        default:
                            Debug.WriteLine("");
                            break;
                    }
                    switch (BPECode.Substring(1, 1).ToUpper())
                    {
                        case "2":
                            Equipment = "A320";
                            break;
                        case "5":
                            Equipment = "E190";
                            break;
                        default:
                            Equipment = "";
                            Debug.WriteLine("");
                            break;
                    }
                    switch (BPECode.Substring(2, 1).ToUpper())
                    {
                        case "C":
                            Position = "CA";
                            break;
                        case "F":
                            Position = "FO";
                            break;
                        case "A":
                            Position = "FA";
                            break;
                        default:
                            Debug.WriteLine("");
                            break;
                    }
                }

                using (new Impersonator("APP_ReserverGrid", "jetblue", "ChuckCookApps!"))
                {
                    RsvGridDataContext db = new RsvGridDataContext();

                    var varRAV =
                        from foundRAV in db.vwReserveGrids
                        where foundRAV.PositionCode == BPECode &&
                              foundRAV.ReserveDate == RAVDate
                        select foundRAV;

                    if (varRAV.Count() > 0)
                    {
                        msgRAV += "Reserve Availablity for: " + RAVDate.ToShortDateString() + " " + Base + " " + Equipment + " " + Position + ",";
                        foreach (var RAV in varRAV)
                        {
                            // Setup ACARS Message
                            msgRAV += ",Open Duty Periods: " + RAV.OpenDutyPeriods +
                                      ",Avail Reserves:  " + RAV.AvailReserves +
                                      ",Net Reserves: " + RAV.NetReserves +
                                      ",Planned Reserve MIN: " + RAV.ReserveRequirement;
                            Debug.Write(" ");

                        }
                        Debug.Write(" ");
                        msgRAV += ",,";
                    }
                    else
                        msgRAV += ",,NO RESERVE AVAIL FOUND FOR " + Base + " " + Equipment + " " + Position + ",";
                    }

            //    if (Position != "FA")
            //    {

            //        ChucksClassLibrary.prodCrew_v3.OpenTimeDetail[] response = ChucksWSH.GetOpenTimeDetail_30(RAVDate, Base, Position, Equipment);

            //        if (response != null)
            //        {
            //            msgRAV += "Reserve Availablity for: " + RAVDate.ToShortDateString() + " " + Base + " " + Equipment + " " + Position + ",";
            //            foreach (var pairing in response)
            //            {
            //                // Setup ACARS Message
            //                msgRAV += "," + pairing.PairingKey.PairingNumber + " " + pairing.PairingKey.Date.ToShortDateString();
            //                Debug.Write(" ");

            //            }
            //            Debug.Write(" ");
            //            msgRAV += ",,";
            //        }
            //        else
            //            msgRAV += ",,NO RESERVE AVAIL FOUND FOR " + Base + " " + Equipment + " " + Position + ",";
                    
            //    }
            //    else
            //    {
            //        foreach (var FAPos in FAPositions)
            //        {
            //            ChucksClassLibrary.prodCrew_v3.OpenTimeDetail[] response = ChucksWSH.GetOpenTimeDetail_30(RAVDate, Base, FAPos, Equipment);

            //            if (response != null)
            //            {
            //                msgRAV += "OPEN TIME for: " + RAVDate.ToShortDateString() + " " + Base + " " + Equipment + " " + FAPos;
            //                foreach (var pairing in response)
            //                {
            //                    // Setup ACARS Message
            //                    msgRAV += "," + pairing.PairingKey.PairingNumber + " " + pairing.PairingKey.Date.ToShortDateString();
            //                    Debug.Write(" ");

            //                }
            //                Debug.Write(" ");
            //                msgRAV += ",,";
            //            }
            //            else
            //                msgRAV += ",,NO RESERVE AVAIL FOUND FOR " + Base + " " + Equipment + " " + FAPos + ",";
            //        }
            //    }

                 return msgRAV;
            }

            catch (Exception err)
            {
                Debug.WriteLine("AREQ RAV Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ RAV Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_FLTSUM_Req(string arrACM, DateTime RequestDate, string ReplyAddress, string CommandSent)
        {
            try
            {
                ChucksWebService.ChucksWebService CWS = new ChucksWebService.ChucksWebService();
                ChucksStringHander CSH = new ChucksStringHander();

                    string msgFLTSUM = "THIS IS NOT A LEGAL RELEASE,";
                    //turn Flight Num into an int to get rid of zero padding
                    int intFltNum = Int16.Parse(arrACM);
                    Regex rgxJetblueEmail = new Regex(@".+@JETBLUE.COM", RegexOptions.Singleline);
                    Match IsEmail = rgxJetblueEmail.Match(ReplyAddress.ToUpper());
                    bool allowed = false;
                    if (IsEmail.Success)
                    {
                        allowed =
                        (ChucksMH.IsEmailInGroup(ReplyAddress, "FLTOPSDUTY") ||
                         ChucksMH.IsEmailInGroup(ReplyAddress, "ChiefPilots") ||
                         ChucksMH.IsEmailInGroup(ReplyAddress, "BlueChkAmnE190") ||
                         ChucksMH.IsEmailInGroup(ReplyAddress, "BlueChkAmnA320") ||
                         ChucksMH.IsEmailInGroup(ReplyAddress, "Flight Ops Team") ||
                        (ReplyAddress == "CHARLES.COOK@JETBLUE.COM") ||
                        (ReplyAddress == "BRIAN.NORTH@JETBLUE.COM"));
                    }

                    using (new Impersonator("APP_AREQ2", "jetblue", "HappyJetting!10"))
                    {
                        ReleaseViewsDataContext ReleaseView = new ReleaseViewsDataContext();

                        var varRelease =
                            from foundReleases in ReleaseView.vw_DispatchReleaseReportings
                            where foundReleases.FltNo == intFltNum.ToString() &&
                                  foundReleases.FlightDate == RequestDate
                            orderby foundReleases.Version descending
                            select foundReleases;

                        if (varRelease.Count() > 0)
                        {

                            foreach (var row in varRelease)
                            {
                                var varMEL =
                                        from foundMELS in ReleaseView.vw_DispatchReleaseReportingMELs
                                        where foundMELS.DispatchReleaseReportingID == row.DispatchReleaseID
                                        select foundMELS;

                                string ETE = row.BurnTime.ToString().Insert(row.BurnTime.ToString().Length - 2, ":");
                                msgFLTSUM += ",RELEASE FOUND: " + DateTime.Parse(row.FlightDate.ToString()).ToShortDateString() +
                                            ",FLT: " + row.FltNo + " " + row.DepCity + "-" + row.ArrCity + " VER: " + row.Version +
                                            ",TAIL: " + row.FlightTail +
                                            ",STD: " + row.STD + "Z" + "  STA: " + row.STA + "Z" +
                                            ",ETD: " + row.ETD + "Z" + "  ETA: " + row.ETA + "Z" +
                                            ",MOT: " + row.MOT + "Z" + "  ETE: " + ETE +
                                            ",DISP: " + row.DESK + " " + row.Dispatcher.Replace(',', '.') +
                                            ",PHONE: " + GetDispPhone(row.DESK) +
                                            ",Altn1: " + row.Alternate + "  Altn2: " + row.Alternate2 +
                                            ",BURN: " + row.BurnFuel + "  RESV: " + row.RsvFuel +
                                            ",ALTNFuel: " + row.AltnFuel + "  ADD: " + row.DispFuel +
                                            ",TOTAL: " + row.RampFuel + "  ZFW: " + row.ZFWWt +
                                            ",EFOB: " + row.EFOBFuel + "  LNDWT: " + row.LDW +
                                            "," + row.Altitude + "  PAX: " + row.PassTotal +
                                            ",Route: " + row.Route +
                                            ",,MEL List:";
                                if (varMEL.Count() > 0)
                                {
                                    foreach (var MEL in varMEL)
                                    {
                                        string MELDate = "";
                                        if (MEL.MELItemExpireDate != null)
                                            MELDate = DateTime.Parse(MEL.MELItemExpireDate.ToString()).ToShortDateString();
                                        else
                                            MELDate = "No Date Found";

                                        msgFLTSUM += "," + MEL.MELItem + "  " + MEL.MELItemDesc + "  " + MELDate;
                                    }
                                }
                                else
                                {
                                    msgFLTSUM += ",No MELs Found";
                                }

                                //Crew Section
                                ChucksClassLibrary.prodCrew_v3.FlightCrewmember[] CrewMember = ChucksWSH.GetFlightCrew_30("B6", row.DepCity, row.ArrCity, row.FltNo, (DateTime)row.FlightDate);
                                if (CrewMember != null)
                                {
                                    msgFLTSUM += ",";
                                    string DeadHead = "  ";

                                    for (int x = 0; x < CrewMember.Length; x++)
                                    {
                                        if (CrewMember[x].IsDeadHead == true) DeadHead = "DH";
                                        else DeadHead = "  ";
                                        if (allowed && IsEmail.Success) //Includes seniority and picture
                                        {
                                            msgFLTSUM += ",<a href=\"mailto:AREQ@jetblue.com?subject=AREQ PIC " + CrewMember[x].CrewmemberId + "\">" + CSH.PadStringWithZeros(CrewMember[x].CrewmemberId, 5) + "</a> "  + DeadHead + " " + CrewMember[x].Position + " " + CrewMember[x].Senority + " - " + CrewMember[x].LastName + "." + CrewMember[x].FirstName;
                                        }
                                        else if
                                         (IsEmail.Success) //Includes picture but not Seniority
                                        {
                                            msgFLTSUM += ",<a href=\"mailto:AREQ@jetblue.com?subject=AREQ PIC " + CrewMember[x].CrewmemberId + "\">" + CSH.PadStringWithZeros(CrewMember[x].CrewmemberId, 5) + "</a> " + DeadHead + " " + CrewMember[x].Position + " - " + CrewMember[x].LastName + "." + CrewMember[x].FirstName;
                                        }
                                        else //No picture no seniority
                                        {
                                            msgFLTSUM += "," + CSH.PadStringWithZeros(CrewMember[x].CrewmemberId, 5) + " " + DeadHead + " " + CrewMember[x].Position + " - " + CrewMember[x].LastName + "." + CrewMember[x].FirstName;
                                        }
                                    }
                                }
                                DateTime FltDate = (DateTime)row.FlightDate;
                                DateTime StartTime = DateTime.ParseExact(FltDate.ToString("MM/dd/yyyy") + " " + row.STD, "MM/dd/yyyy HHmm", System.Globalization.DateTimeFormatInfo.InvariantInfo) - new TimeSpan(0, 6, 0, 0);
                                DateTime EndTime = StartTime + new TimeSpan(0, 12, 0, 0);

                                ChucksClassLibrary.prodFlight_v3.PassengerDetail[] PaxDetails = ChucksWSH.prd_GetPaxDetails_30("B6", row.DepCity, row.ArrCity, row.FltNo, (DateTime)row.FlightDate);
                                ChucksClassLibrary.prodFlight_v3.FlightDetail[] WebSvcFligthts = ChucksWSH.prd_GetFlightsByTail_30(row.FlightTail, StartTime, EndTime);
                                if (WebSvcFligthts != null)
                                {
                                    foreach (ChucksClassLibrary.prodFlight_v3.FlightDetail Flt in WebSvcFligthts)
                                    {
                                        if ((int.Parse(Flt.FlightNumber).ToString() == row.FltNo) && (Flt.DepartureAirport == row.DepCity))
                                        {
                                        //    DateTime TestZulu = DateTime.Now;
                                       //     if (true) msgFLTSUM += ",,EDCT: " + TestZulu.ToString("MM/dd/yy hhmm") + "z";
                                       //     else msgFLTSUM += ",,EDCT: NO EDCT FOUND";

                                            if (Flt.EDCTZulu != null)
                                            {
                                                //Converts Nullable to not null DateTime
                                                DateTime EDCTZulu = Flt.EDCTZulu ?? DateTime.MinValue;
                                                msgFLTSUM += ",,EDCT: " + EDCTZulu.ToString("MM/dd/yy hhmm") + "z";
                                            }
                                            else msgFLTSUM += ",,EDCT: NO EDCT FOUND";

                                            msgFLTSUM += ",,Departure Gate: " + Flt.DepartureGate;
                                            msgFLTSUM += ",Arrival Gate: " + Flt.ArrivalGate;
                                            
                                            //Door Codes
                                            ChucksWebService.objDoorCodes[] DepCodes = CWS.GetDoorCode(Flt.DepartureAirport);
                                            ChucksWebService.objDoorCodes[] ArrCodes = CWS.GetDoorCode(Flt.ArrivalAirport);
                                            foreach (var code in DepCodes)
                                            {
                                                msgFLTSUM += ",  Door Code(s): "+code.City + "-" + code.DoorCode + "-" + code.Comment;
                                            }

                                            foreach (var code in ArrCodes)
                                            {
                                                msgFLTSUM += ",  Door Code(s): " + code.City + "-" + code.DoorCode + "-" + code.Comment;
                                            }

                                            //INBOUND SECTION
                                            var query = from FlightDetail in WebSvcFligthts
                                                        orderby FlightDetail.CurrentDepartureDateTime
                                                        select FlightDetail;

                                            string DepartureTime = ""; string ArrivalTime = "";
                                            msgFLTSUM += ",,INBOUND FLIGHT INFO: ";
                                            msgFLTSUM += ",(S)=SCHEDULED (E)=ESTIMATED";
                                            msgFLTSUM += ",FLT  PAIR    STATUS    (S)ETD   (S)ETA,";

                                            foreach (var item in query)
                                            {
                                                if (item.CurrentDepartureDateTime != item.ScheduledDepartureDateTime)
                                                    DepartureTime = "(E)" + item.CurrentDepartureDateTime.ToString("HHmm") + "L";
                                                else
                                                    DepartureTime = "(S)" + item.ScheduledDepartureDateTime.ToString("HHmm") + "L";

                                                if (item.CurrentArrivalDateTime != item.ScheduledArrivalDateTime)
                                                    ArrivalTime = "(E)" + item.CurrentArrivalDateTime.ToString("HHmm") + "L";
                                                else
                                                    ArrivalTime = "(S)" + item.ScheduledArrivalDateTime.ToString("HHmm") + "L";

                                                msgFLTSUM += item.FlightNumber + " " +
                                                           item.DepartureAirport + "-" +
                                                           item.ArrivalAirport + " " +
                                                           item.FlightStatus.PadRight(9, ' ') + " " +
                                                           DepartureTime + " " +
                                                           ArrivalTime + ",";
                                            }
                                        }
                                    }
                                }

                                if (PaxDetails != null)
                                {
                                    foreach (ChucksClassLibrary.prodFlight_v3.PassengerDetail Pax in PaxDetails)
                                    {
                                        if (Pax.PassengerGroup == "booked_pax")
                                        {
                                            msgFLTSUM += ",,Booked PAX" + " : " + Pax.PassengerCount;
                                        }
                                        if (Pax.PassengerGroup == "booked_pad")
                                        {
                                            msgFLTSUM += ",Booked STBY" + " : " + Pax.PassengerCount;
                                        }
                                    }
                                }

                                ChucksWeatherHandler CWXH = new ChucksWeatherHandler();
                                try
                                {
                                    //Departure WX
                                    nsMETAR.METAR[] DepMETAR = null;
                                    if (row.DepCity.Length == 3)
                                        DepMETAR = CWXH.GetMETAR_IATA(row.DepCity);
                                    else if (row.DepCity.Length == 4)
                                        DepMETAR = CWXH.GetMETAR_ICAO(row.DepCity);
                                    nsTAF.TAF[] DepTAF = null;
                                    if (row.DepCity.Length == 3)
                                        DepTAF = CWXH.GetTAF_IATA(row.DepCity);
                                    else if (row.DepCity.Length == 4)
                                        DepTAF = CWXH.GetTAF_ICAO(row.DepCity);
                                    
                                    //Arrival WX
                                    nsMETAR.METAR[] ArrMETAR = null;
                                    if (row.ArrCity.Length == 3)
                                        ArrMETAR = CWXH.GetMETAR_IATA(row.ArrCity);
                                    else if (row.ArrCity.Length == 4)
                                        ArrMETAR = CWXH.GetMETAR_ICAO(row.ArrCity);
                                    nsTAF.TAF[] ArrTAF = null;
                                    if (row.ArrCity.Length == 3)
                                        ArrTAF = CWXH.GetTAF_IATA(row.ArrCity);
                                    else if (row.ArrCity.Length == 4)
                                        ArrTAF = CWXH.GetTAF_ICAO(row.ArrCity);

                                    //TO Alternate WX
                                    nsMETAR.METAR[] TOAltMETAR = null;
                                    if (row.TOAlternate.Length == 3)
                                        TOAltMETAR = CWXH.GetMETAR_IATA(row.TOAlternate);
                                    else if (row.TOAlternate.Length == 4)
                                        TOAltMETAR = CWXH.GetMETAR_ICAO(row.TOAlternate);
                                    nsTAF.TAF[] TOAltTAF = null;
                                    if (row.TOAlternate.Length == 3)
                                        TOAltTAF = CWXH.GetTAF_IATA(row.TOAlternate);
                                    else if (row.TOAlternate.Length == 4)
                                        TOAltTAF = CWXH.GetTAF_ICAO(row.TOAlternate);
                                    
                                    //Alternate WX
                                    nsMETAR.METAR[] AltMETAR = null;
                                    if (row.Alternate.Length == 3)
                                        AltMETAR = CWXH.GetMETAR_IATA(row.Alternate);
                                    else if (row.Alternate.Length == 4)
                                        AltMETAR = CWXH.GetMETAR_ICAO(row.Alternate);
                                    nsTAF.TAF[] AltTAF = null;
                                    if (row.Alternate.Length == 3)
                                        AltTAF = CWXH.GetTAF_IATA(row.Alternate);
                                    else if (row.Alternate.Length == 4)
                                        AltTAF = CWXH.GetTAF_ICAO(row.Alternate);

                                    //Alternate2 Wx
                                    nsMETAR.METAR[] Alt2METAR = null;
                                    if (row.Alternate2.Length == 3)
                                        Alt2METAR = CWXH.GetMETAR_IATA(row.Alternate2);
                                    else if (row.Alternate2.Length == 4)
                                        Alt2METAR = CWXH.GetMETAR_ICAO(row.Alternate2);
                                    nsTAF.TAF[] Alt2TAF = null;
                                    if (row.Alternate2.Length == 3)
                                        Alt2TAF = CWXH.GetTAF_IATA(row.Alternate2);
                                    else if (row.Alternate2.Length == 4)
                                        Alt2TAF = CWXH.GetTAF_ICAO(row.Alternate2);


                                    msgFLTSUM += ",,CURRENT WX:";
                                    if (DepMETAR != null) msgFLTSUM += ",METAR: " + DepMETAR[0].raw_text;
                                    if (ArrMETAR != null) msgFLTSUM += ",METAR: " + ArrMETAR[0].raw_text;
                                    if (TOAltMETAR != null) msgFLTSUM += ",METAR: " + TOAltMETAR[0].raw_text;
                                    if (AltMETAR != null) msgFLTSUM += ",METAR: " + AltMETAR[0].raw_text;
                                    if (Alt2METAR != null) msgFLTSUM += ",METAR: " + Alt2METAR[0].raw_text;
                                    msgFLTSUM += ",,FORECAST WX:";
                                    if (DepTAF != null) msgFLTSUM += ",TAF: " + DepTAF[0].raw_text;
                                    if (ArrTAF != null) msgFLTSUM += ",TAF: " + ArrTAF[0].raw_text;
                                    if (TOAltTAF != null) msgFLTSUM += ",TAF: " + TOAltTAF[0].raw_text;
                                    if (AltTAF != null) msgFLTSUM += ",TAF: " + AltTAF[0].raw_text;
                                    if (Alt2TAF != null) msgFLTSUM += ",TAF: " + Alt2TAF[0].raw_text;
                                }
                                catch
                                {
                                    msgFLTSUM += "Error getting TAF/METAR Data,";
                                }

                            }
                        }
                        else //No release found
                        {
                            //Check for subscription
                            string Command = Regex.Match(CommandSent, @"^(\w+\b.*?){1}").ToString();
                            if (IsEmail.Success)
                            {
                                msgFLTSUM = "No release info found for Flt: " + arrACM + 
                                             ",,the release will be automatically delivered,to this email address if it becomes available,in the next two hours.,";

                                //Create Subscription
                                tblAreqSubscription newsub = new tblAreqSubscription();

                                newsub.CommandSent = CommandSent;
                                newsub.AreqCommand = Command;
                                newsub.SubActive = true;
                                newsub.SubAddress = ReplyAddress;
                                newsub.SubExpiriation = DateTime.Now + new TimeSpan(0, 120, 0);
                                newsub.SubStartTime = DateTime.Now;
                                newsub.SubType = "EMAIL";

                                using (new Impersonator("APP_AREQ2", "jetblue", "HappyJetting!10"))
                                {
                                    using (ProdFltOpsDBDataContext db = new ProdFltOpsDBDataContext())
                                    {
                                        db.tblAreqSubscriptions.InsertOnSubmit(newsub);
                                        db.SubmitChanges();
                                    }
                                }

                            }
                            else //Not an email
                                msgFLTSUM = "No release info found for Flt: " + arrACM + ",,";
                            
                        }
                    }
                    return msgFLTSUM;
                }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ EDCT Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ EDCT Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());

                //string LogFile = LogFileHeader + DateTime.Now.ToString("MMMyy") + ".txt";
               // System.IO.File.AppendAllText(LogFile, DateTime.Now + ": " + CommandSent + err.ToString() + Environment.NewLine);

                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_TAXI_Req(string INRAirport, string ACMTailNum, string CommandSent)
        {

            int TaxiOutPeriod = 90;  //Taxi Out Time Calculated on flights in the last TakeOutPeriod minutes
            DateTime TaxiOutWindow = DateTime.Now - new TimeSpan(0, TaxiOutPeriod, 0);
            int TaxiOutCalc = 0;
            int TaxiOutCounter = 0;
            DateTime StartQueryTime = DateTime.Now - new TimeSpan(6, 0, 0);
            DateTime EndQueryTime = DateTime.Now + new TimeSpan(6,0,0);
            try
            {
                string msgTAXI =  "Taxi City:" + INRAirport + ",,";

                double timeOffset = ChucksWSH.GetVariance(INRAirport).TotalMinutes;
                 
                DateTime serverTime = DateTime.Now.ToUniversalTime();
                DateTime adjustedTaxiOutWindow = serverTime - new TimeSpan(0, TaxiOutPeriod, 0);

                //ChucksClassLibrary.prodFlight_v2_1.FlightDetail[] DepResp = ChucksWSH.GetFlightDetails(INRAirport, TaxiOutWindow, ChucksClassLibrary.prodFlight_v2_1.FlightDirection.DepartingFrom, ChucksClassLibrary.prodFlight_v2_1.FlightStatus.ALL);
                ChucksClassLibrary.prodFlight_v3.FlightDetail[] DepResp = ChucksWSH.prd_GetFlightsByDepartureAirport_30(INRAirport, StartQueryTime, EndQueryTime);
                
                if (DepResp == null)
                {
                    msgTAXI += "No data found";
                    return msgTAXI;
                }
                else
                {
                    TimeSpan LastTaxiTime = new TimeSpan(0, 0, 0); DateTime LastDepartureTime = DateTime.MinValue;
                    for (int x = 0; x < DepResp.Length; x++)  //Find Taxi Out Times
                    {
                        //if (DepResp[x].OutTime != DateTime.MinValue)  //Aircraft has and OUT time posted
                        if (DepResp[x].OutLocal != null)  //Aircraft has and OUT time posted
                        {
                            //if (DepResp[x].OffTime > LastDepartureTime)
                            if ((DepResp[x].OffLocal != null) && (DepResp[x].OffLocal > LastDepartureTime))
                            {
                                //LastDepartureTime = DepResp[x].OffTime;
                                //LastTaxiTime = DepResp[x].OffTime - DepResp[x].OutTime;
                                LastDepartureTime = (DateTime)DepResp[x].OffLocal;
                                LastTaxiTime = (DateTime)DepResp[x].OffLocal - (DateTime)DepResp[x].OutLocal;
                            }
                            //if (DepResp[x].OffTime.AddMinutes(-timeOffset) > adjustedTaxiOutWindow) //Aircraft has an OFF Time within window
                            if ((DepResp[x].OffZulu != null) && (DepResp[x].OffZulu > adjustedTaxiOutWindow)) //Aircraft has an OFF Time within window
                            {
                                //TimeSpan TaxiTime = (DepResp[x].OffTime - DepResp[x].OutTime);
                                TimeSpan TaxiTime = ((DateTime)DepResp[x].OffLocal - (DateTime)DepResp[x].OutLocal);
                                TaxiOutCalc = TaxiOutCalc + Convert.ToInt16(TaxiTime.TotalMinutes);
                                TaxiOutCounter++;
                            }
                        }
                    }
                    if (TaxiOutCounter != 0) TaxiOutCalc = TaxiOutCalc / TaxiOutCounter;  //Divide by number of flights found with an Taxi Time
                    msgTAXI += "Avg Taxi last 90min,at: " + INRAirport + " " + TaxiOutCalc + " minutes,,";
                    if (LastDepartureTime != DateTime.MinValue)
                        msgTAXI += "Last JB OFF at " + INRAirport + ",was at " + LastDepartureTime.ToString("HHmm") + " Local,Taxied " + LastTaxiTime.TotalMinutes + " minutes,";
                    else
                        msgTAXI += "NO JB DEP LAST 3 HRS";
                    return msgTAXI;
                }
                
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ TAXI Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ TAXI Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_SEDCT_Req(string[] arrACM, string ACMTailNum, string CommandSent)
        {
            try
            {
                string msgEDCT = "";
                string dtCTD;
                string Command = arrACM[0];
                int intAvgDelays = 0; int intDelay = 0; int intTotalDelayMinutes = 0;
                TimeSpan tsDelay = new TimeSpan(0,0,0);
                int ControlCount = 0;
                

                string[] EDCTREQ = new string[arrACM.Length - 1];
                for (int x = 1; x < arrACM.Length; x++)
                {
                    EDCTREQ[x - 1] = arrACM[x]; //This strips the text "EDCT" from the request
                }

                Regex cmdEmailSub = new Regex(@"@JETBLUE");
                Match mtchEmailSub = cmdEmailSub.Match(ACMTailNum);

                Regex cmdEDCT = new Regex(@"^(?<FltNumber>\d{1,4})|(?<City>[A-Za-z]{3,4})");
                Match mtchEDCT = cmdEDCT.Match(EDCTREQ[0]);

                string EDCTCity = mtchEDCT.Groups["City"].ToString();
                string EDCTFlt = mtchEDCT.Groups["FltNumber"].ToString();

                using (new Impersonator("APP_EDCT", "jetblue", "HappyJetting!10"))
                {
                    tblNewEDCTDataContext db = new tblNewEDCTDataContext();
                    if (EDCTCity != "")
                    {
                        var varEDCT =
                            from foundEDCTs in db.tbl_NEWEDCTs
                            where foundEDCTs.DEST == EDCTCity
                            select foundEDCTs;

                        msgEDCT += "DO NOT MAKE DECISIONS BASED ON THIS MSG" +
                                   ",WITHOUT CONTACTING THE SOC";

                        foreach (var row in varEDCT)
                        {
                            // Setup ACARS Message
                            DateTime dtIGTD = (DateTime)row.IGTD;

                            if (row.CTD != null)
                            {
                                DateTime dtCTDz = (DateTime)row.CTD;


                                ControlCount++;
                                tsDelay = dtCTDz - dtIGTD;
                                intDelay = Convert.ToInt32(tsDelay.TotalMinutes);
                                intTotalDelayMinutes += intDelay;
                                intAvgDelays = (intTotalDelayMinutes) / ControlCount;

                                dtCTD = dtCTDz.ToString("MM/dd/yy HHmm") + "Z";
                                msgEDCT += "Sched: " + dtIGTD.ToString("MM/dd/yy HHmm") + "Z" +
                                        ",Flt: " + row.FL +
                                        ",City Pair: " + row.ORIG + "-" + row.DEST +
                                        ",EDCT: " + dtCTD + ",,";
                            }

                            if (varEDCT.Count() == 0) msgEDCT += ",,NO EDCT's FOUND in " + EDCTCity;
                        }
                        Debug.Write(" ");
                    }
                    else if (EDCTFlt != "")
                    {
                        var varEDCT =
                            from foundEDCTs in db.tbl_NEWEDCTs
                            where foundEDCTs.FL == EDCTFlt &&
                                  foundEDCTs.CTD != null
                            select foundEDCTs;

                        msgEDCT += "DO NOT MAKE DECISIONS BASED ON THIS MSG" +
                                   ",WITHOUT CONTACTING THE SOC";

                        foreach (var row in varEDCT)
                        {
                            // Setup ACARS Message
                            DateTime dtIGTD = (DateTime)row.IGTD;
                            DateTime dtCTDz = (DateTime)row.CTD;

                            dtCTD = dtCTDz.ToString("MM/dd/yy HHmm") + "Z";


                            msgEDCT += ",,Sched: " + dtIGTD.ToString("MM/dd/yy HHmm") + "Z" +
                                       ",Flt: " + row.FL +
                                       ",City Pair: " + row.ORIG + "-" + row.DEST +
                                       ",EDCT: " + dtCTD + ",,";

                            if (Command == "SEDCT")
                            {

                                var ExistingSub = db.tbl_Subscriptions
                                   .SingleOrDefault(Flt =>
                                   Flt.IGTD == row.IGTD &&
                                   Flt.FL == row.FL &&
                                   Flt.ORIG == row.ORIG &&
                                   Flt.DEST == row.DEST &&
                                   ((Flt.EMAIL == ACMTailNum) || (Flt.TAILNUMBER == ACMTailNum)));

                                if (ExistingSub == null)
                                {

                                    //Add Subscription
                                    tbl_Subscription newSub = new tbl_Subscription();
                                    newSub.IGTD = (DateTime)row.IGTD;
                                    newSub.FL = row.FL;
                                    newSub.ORIG = row.ORIG;
                                    newSub.DEST = row.DEST;
                                    newSub.CTD = row.CTD;
                                    if (mtchEmailSub.Success)
                                    {
                                        newSub.EMAIL = ACMTailNum;
                                        newSub.TAILNUMBER = "";
                                        newSub.EXPIRATION = (DateTime)row.CTD + new TimeSpan(0, 30, 0);
                                        newSub.SUB_INIT = DateTime.UtcNow;
                                    }
                                    else
                                    {
                                        newSub.TAILNUMBER = ACMTailNum;
                                        newSub.EMAIL = "";
                                        newSub.EXPIRATION = (DateTime)row.CTD + new TimeSpan(0, 30, 0);
                                        newSub.SUB_INIT = DateTime.UtcNow;

                                        //Commented out to try and fix SEDCT from the aircraft.  Guessing that an error here was preventing subscriptions from being created.
                                        //ChucksClassLibrary.prodFlight_v3.FlightDetail[] FltsByTail = ChucksWSH.prd_GetFlightsByTail_30(newSub.TAILNUMBER, DateTime.Now, DateTime.Now + new TimeSpan(6, 0, 0));
                                        //if (FltsByTail != null)
                                        //{
                                        //    foreach (ChucksClassLibrary.prodFlight_v3.FlightDetail Flt in FltsByTail)
                                        //    {
                                        //        if (Flt.EstimatedArrivalZulu < newSub.EXPIRATION)
                                        //            newSub.EXPIRATION = Flt.EstimatedArrivalZulu;
                                        //    }
                                        //}

                                    }
                                    newSub.UPD_TIME = DateTime.UtcNow;

                                    db.tbl_Subscriptions.InsertOnSubmit(newSub);
                                    db.SubmitChanges();

                                    msgEDCT += ",Subscription was added that will expire at: " + newSub.EXPIRATION.ToString("HHmm") + "Z";
                                    msgEDCT += ",,It is now: : " + DateTime.UtcNow.ToString("HHmm") + "Z";
                                }
                                Counters.Where(p => p.CounterName == "SEDCT").SingleOrDefault().CurrentCount += 1;
                            }
                        }
                        //No EDCT's found
                        if (varEDCT.Count() == 0) msgEDCT += ",,NO EDCT's FOUND for Flt:  " + EDCTFlt;
                    }
                }
                return msgEDCT;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ SEDCT Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ SEDCT Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_Doors_Req(string arrACM, string ACMTailNum, string CommandSent)
        {
            try
            {
                string msgDoors = "";

                string DoorCity = arrACM;

                using (new Impersonator("APP_AREQ2", "jetblue", "HappyJetting!10"))
                {
                   
                    ProdFltOpsDBDataContext db = new ProdFltOpsDBDataContext();

                    if (DoorCity == "ALL")
                    {
                        var varDoors =
                            from foundDoors in db.tblDoorCodes
                            select foundDoors;

                        if (varDoors.Count() != 0)
                        {

                            foreach (var row in varDoors)
                            {
                                // Setup ACARS Message
                                msgDoors += ",City: " + row.City + " Code: " + row.DoorCode + " " + row.Comments;
                            }
                            Debug.Write(" ");


                            //No Doors's found
                        }
                        else
                            msgDoors += ",,NO DOOR CODES's FOUND for:  " + DoorCity;
                    }
                    else
                    {
                        var varDoors =
                            from foundDoors in db.tblDoorCodes
                            where foundDoors.City == DoorCity
                            select foundDoors;

                        if (varDoors.Count() != 0)
                        {
                            msgDoors += ",City: " + DoorCity;

                            foreach (var row in varDoors)
                            {
                                // Setup ACARS Message
                                msgDoors += ",Code: " + row.DoorCode + " " + row.Comments;
                            }
                            Debug.Write(" ");


                            //No Doors's found
                        }
                        else
                            msgDoors += ",,NO DOOR CODES's FOUND for:  " + DoorCity;
                    }

                    msgDoors += ",,SEND UPDATES TO EMAIL BELOW,ALSO TRY - AREQ DOORS ALL,";
                }
                return msgDoors;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ DOORS Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ DOORS Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_EDCTDELAYS_Req(string arrACM, string ACMTailNum, string CommandSent)
        {
            try
            {
                string msgEDCT = "";
                int intAvgDelays = 0; int intDelay = 0; int intTotalDelayMinutes = 0;
                TimeSpan tsDelay = new TimeSpan(0, 0, 0);
                int ControlCount = 0;

                string EDCTCity = arrACM;

                //LINQ DELETE Section
                using (new Impersonator("APP_EDCT", "jetblue", "HappyJetting!10"))
                {
                    tblNewEDCTDataContext db = new tblNewEDCTDataContext();
                    if (EDCTCity != "")
                    {
                        var varEDCT =
                            from foundEDCTs in db.tbl_NEWEDCTs
                            where foundEDCTs.DEST == EDCTCity
                            select foundEDCTs;

                        foreach (var row in varEDCT)
                        {
                            // Setup ACARS Message
                            DateTime dtIGTD = (DateTime)row.IGTD; // DateTime.ParseExact(row.IGTD, "yyyyMMddHHmm", null);

                            if (row.CTD != null)
                            {
                                DateTime dtCTDz = (DateTime)row.CTD;//.ParseExact(row.CTD, "yyyyMMddHHmm", null);


                                ControlCount++;
                                tsDelay = dtCTDz - dtIGTD;
                                intDelay = Convert.ToInt32(tsDelay.TotalMinutes);
                                intTotalDelayMinutes += intDelay;
                                intAvgDelays = (intTotalDelayMinutes) / ControlCount;
                            }
                        }
                        if (ControlCount == 0) msgEDCT = "NO EDCT's FOUND in " + EDCTCity;
                        else
                        {
                            msgEDCT += "Delay info for: " + EDCTCity;
                            msgEDCT += ",,Total Controlled Flts: " + ControlCount;
                            msgEDCT += ",Total Delay Min: " + intTotalDelayMinutes;
                            msgEDCT += ",Average Delay Min: " + intAvgDelays;
                        }
                        //Add PROGRAMS INFORMATION
                        msgEDCT += ",," + ParseACM_PROGRAMS_Req(EDCTCity, ACMTailNum, CommandSent);

                        Debug.Write(" ");
                    }
                }
                return msgEDCT;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ EDCT Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ EDCT Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_PROGRAMS_Req(string arrACM, string ACMTailNum, string CommandSent)
        {
            try
            {
                //ConvertTime CT = new ConvertTime();
                
                string msgPROGRAMS = "PgmAirport: " + arrACM + ","; ;

                //Deserialize
                XmlSerializer serializer = new XmlSerializer(typeof(FSM_BROADCAST));
                TextReader tr = new StreamReader(@"C:\Temp\FSM.xml");
                FSM_BROADCAST Programs = (FSM_BROADCAST)serializer.Deserialize(tr);
                tr.Close();

                bool PgmFound = false;

                for (int x = 0; x < Programs.ControlElements.GetLength(0); x++)
                {
                    if (Programs.ControlElements[x].ElemName == arrACM.ToLower())
                    {
                        PgmFound = true;
                        for (int y = 0; y < Programs.ControlElements[x].Programs.GetLength(0); y++)
                        {
                            msgPROGRAMS = msgPROGRAMS + ",PgmType:" + Programs.ControlElements[x].Programs[y].ProgramType.ToString() +
                                                        ",PgmStatus:" + Programs.ControlElements[x].Programs[y].ProgramStatus.ToString() +
                                                        ",PgmStart:" + ChucksCT.ConvertyyyymmddHHmmss(Programs.ControlElements[x].Programs[y].ProgramStart).ToString("MM/dd/yy HHmm") + "Z" +
                                                        ",PgmEnd:" + ChucksCT.ConvertyyyymmddHHmmss(Programs.ControlElements[x].Programs[y].ProgramEnd).ToString("MM/dd/yy HHmm") + "Z,";
                        }

                    }
                }
                                   
                if ( PgmFound == false ) msgPROGRAMS = msgPROGRAMS + "NO ACTIVE PROGRAMS";

                Debug.WriteLine("");
                return msgPROGRAMS;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ PROGRAMS Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ PROGRAMS Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_TURNS_Req(string INRAirport, string TurnTime, string ACMTailNum, string CommandSent)
        {
            DateTime TimeNow;

            DateTime TimeLater;
            try
            {
                TimeSpan LocalVariance = ChucksWSH.GetVariance(INRAirport);
                DateTime LocalTimeNow = DateTime.UtcNow + LocalVariance;

                if (TurnTime == "") TimeNow = LocalTimeNow;
                else TimeNow = ChucksCT.ConvertHHmmSameDate(TurnTime, LocalTimeNow);

                if (TimeNow < (LocalTimeNow - new TimeSpan(1, 0, 0))) TimeNow = TimeNow + new TimeSpan(24, 0, 0);  //Midnight Logic

                TimeLater = TimeNow + new TimeSpan(3, 0, 0);  //Grab flights for the next 3 hours

                string msgTURNS = "TURNS City:" + INRAirport + " Time: " + TimeNow.ToString("HHmm") + "L " + TimeNow.ToShortDateString() + ",,";

                ChucksClassLibrary.prodFlight_v3.FlightDetail[] OutBoundResp = ChucksWSH.prd_GetFlightsByDepartureAirport_30(INRAirport, TimeNow, TimeLater);
                ChucksClassLibrary.prodFlight_v3.FlightDetail[] InBoundResp = ChucksWSH.prd_GetFlightsByArrivalAirport_30(INRAirport, TimeNow, TimeLater);

                if (OutBoundResp != null)
                {
                    string DepartureTime = "";

                    msgTURNS += ",Flights Departing FROM: " + INRAirport + ",";
                    msgTURNS += ",CTY FLT    STATUS  (S)ETD   GATE   TAIL,";
                    for (int x = 0; x < OutBoundResp.Length; x++)
                    {
                        string TailNum; string Status;
                        if (OutBoundResp[x].FlightStatus.ToString() == "CANCELLED")
                        {
                            TailNum = "   ";
                            Status = "CANCELD";
                        }
                        else if (OutBoundResp[x].FlightStatus.ToString() == "BOARDING")
                        {
                            Status = "BOARDNG";
                            TailNum = InBoundResp[x].TailNumber;
                        }
                        else 
                        {
                            TailNum = OutBoundResp[x].TailNumber;
                            Status = OutBoundResp[x].FlightStatus;
                        }

                        if (OutBoundResp[x].CurrentDepartureDateTime != OutBoundResp[x].ScheduledDepartureDateTime)
                            DepartureTime = "(E)" + OutBoundResp[x].CurrentDepartureDateTime.ToString("HHmm") + "L";
                        else
                            DepartureTime = "(S)" + OutBoundResp[x].ScheduledDepartureDateTime.ToString("HHmm") + "L";

                        if (OutBoundResp[x].FlightStatus.ToString() != "DEPARTED")
                        {
                            msgTURNS += OutBoundResp[x].ArrivalAirport + " F:" + OutBoundResp[x].FlightNumber + " " + Status.PadRight(7, ' ') + " " + DepartureTime + " G:" + OutBoundResp[x].DepartureGate.Trim().PadRight(4, ' ') + " T:" + TailNum + ",";
                        }
                    }
                }
                else
                {
                    msgTURNS += "No Flights Found at " + INRAirport + ",between " + TimeNow.ToShortTimeString() + "-" + TimeLater.ToShortTimeString() + ",";
                }

                if (InBoundResp != null)
                {
                    string ArrivalTime = "";
                    msgTURNS += ",Flights Arriving TO: " + INRAirport+ ",";
                    msgTURNS += ",CTY FLT    STATUS  (S)ETA   GATE   TAIL,";

                    for (int x = 0; x < InBoundResp.Length; x++)
                    {
                        string TailNum;string Status = "";
                        if (InBoundResp[x].FlightStatus.ToString() == "CANCELLED") 
                        {
                            TailNum = "";
                            Status = "CANCELD";
                        }
                        else if (InBoundResp[x].FlightStatus.ToString() == "DEPARTED")
                        {
                            Status = "DEPARTD";
                            TailNum = InBoundResp[x].TailNumber;
                        }
                        else if (InBoundResp[x].FlightStatus.ToString() == "DIVERTED")
                        {
                            Status = "DIVERTD";
                            TailNum = InBoundResp[x].TailNumber;
                        }
                        else
                        {
                            TailNum = InBoundResp[x].TailNumber;
                            Status = InBoundResp[x].FlightStatus;
                        }
                        
                        if (InBoundResp[x].CurrentArrivalDateTime != InBoundResp[x].ScheduledArrivalDateTime)
                            ArrivalTime = "(E)" + InBoundResp[x].CurrentArrivalDateTime.ToString("HHmm") + "L";
                        else
                            ArrivalTime = "(S)" + InBoundResp[x].ScheduledArrivalDateTime.ToString("HHmm") + "L";

                        msgTURNS += InBoundResp[x].DepartureAirport + " F:" + InBoundResp[x].FlightNumber + " " + Status.PadRight(7, ' ') + " " + ArrivalTime + " G:" + InBoundResp[x].ArrivalGate.Trim().PadRight(4, ' ') + " T:" + TailNum + ",";
                    }
                }
                else
                {
                    msgTURNS += "No Flights Found at " + INRAirport + ",between " + TimeNow.ToShortTimeString() + "-" + TimeLater.ToShortTimeString() + ",";
                }

                return msgTURNS;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ TURNS Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ TURNS Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_TIMES_DELAY_Req(string FltNumber, DateTime RequestDate, string ACMTailNum, string REQ_Keyword, string CommandSent)
        {
            try
            {
                DateTime dtReq;
                
                string msgTIMES_DELAY =  "Flt: " + FltNumber + ",";
                if (RequestDate != DateTime.MinValue)
                {
                    dtReq = RequestDate;
                    msgTIMES_DELAY += "Date: " + dtReq.ToShortDateString() + ",,";
                }
                else
                {
                    dtReq = DateTime.Now;
                    msgTIMES_DELAY += "Date: " + dtReq.ToShortDateString() + ",,";
                }

                DateTime dtReqBegin = new DateTime(dtReq.Year, dtReq.Month, dtReq.Day, 0, 0, 0, 0);
                DateTime dtReqEnd = new DateTime(dtReq.Year, dtReq.Month, dtReq.Day, 23, 59, 59, 0);

                ChucksClassLibrary.prodFlight_v3.FlightDetail[] FlightsResponse = ChucksWSH.prd_GetFlightsByFlightNumber_30("", FltNumber, "", "", dtReqBegin, dtReqEnd);
                
                if  ( FlightsResponse == null )
                {
                    msgTIMES_DELAY += " No flight data found";
                    return msgTIMES_DELAY;
                }

                switch (REQ_Keyword)
                {
                    case "TIMES":  //Process a TIMES Request
                    case "DELAY":
                    case "DELAYCODE":
                    case "STIMES":
                        for (int x = 0; x < FlightsResponse.Length; x++)
                        {
                            string OUT; string OFF; string ON; string IN; string strEDCTTime = "" ;
                            if (FlightsResponse[x].OutZulu == null) OUT = "";
                            else OUT = FlightsResponse[x].OutZulu.Value.ToString("HHmm") + "Z"; //.ToString("HHmm")
                            if (FlightsResponse[x].OffZulu == null) OFF = "";
                            else OFF = FlightsResponse[x].OffZulu.Value.ToString("HHmm") + "Z";
                            if (FlightsResponse[x].OnZulu == null) ON = "";
                            else ON = FlightsResponse[x].OnZulu.Value.ToString("HHmm") + "Z";
                            if (FlightsResponse[x].InZulu == null) IN = "";
                            else IN = FlightsResponse[x].InZulu.Value.ToString("HHmm") + "Z";
                            if (FlightsResponse[x].EDCTZulu == null) strEDCTTime = "No EDCT Found";
                            else strEDCTTime = FlightsResponse[x].EDCTZulu.Value.ToString("HHmm") + "Z";

                            //Get Delay Descriptions if not NULL
                            string strDepDelayDesc = "";
                            string strArrDelayDesc = "";
                            if (FlightsResponse[x].DepartureDelayCode.Trim() != "")
                                strDepDelayDesc = GetDelayDescriptions(FlightsResponse[x].DepartureDelayCode.ToString());
                            if (FlightsResponse[x].ArrivalDelayCode.Trim() != "")
                                strArrDelayDesc = GetDelayDescriptions(FlightsResponse[x].ArrivalDelayCode.ToString());
                                
                            msgTIMES_DELAY += FlightsResponse[x].DepartureAirport + "-" + FlightsResponse[x].ArrivalAirport +
                                            ",Status: " + FlightsResponse[x].FlightStatus.ToString() +
                                            ",Tail: " + FlightsResponse[x].TailNumber.ToString() +
                                            ",STD: " + FlightsResponse[x].ScheduledDepartureDateTime.ToString() +
                                            ",ETD: " + FlightsResponse[x].CurrentDepartureDateTime.ToString() +
                                            ",STA: " + FlightsResponse[x].ScheduledArrivalDateTime.ToString() +
                                            ",ETA: " + FlightsResponse[x].CurrentArrivalDateTime.ToString() +
                                            ",DepDelay: " + FlightsResponse[x].DepartureDelayCode.ToString() + " - " + strDepDelayDesc +
                                            ",ArrDelay: " + FlightsResponse[x].ArrivalDelayCode.ToString() + " - " + strArrDelayDesc +
                                            ",DGate " + FlightsResponse[x].DepartureGate.ToString() +
                                            ",AGate " + FlightsResponse[x].ArrivalGate.ToString() +
                                            ",EDCT: " + strEDCTTime +
                                            ",OUT: " + OUT +
                                            ",OFF: " + OFF +
                                            ", ON: " + ON +
                                            ", IN: " + IN +
                                            ",,";
                            if (IN != "")
                            {
                                TimeSpan BlockTime = ((DateTime)FlightsResponse[x].InZulu - (DateTime)FlightsResponse[x].OutZulu);
                                msgTIMES_DELAY += "Block: " + BlockTime.ToString() + ",,";
                            }
                            else // IN is still blank
                            {
                                // Handle STIMES
                                string Command = Regex.Match(CommandSent, @"^(\w+\b.*?){1}").ToString();
                                if (Command == "STIMES")//set subscription
                                {
                                    Regex rgxJetblueEmail = new Regex(@".+@JETBLUE.COM", RegexOptions.Singleline);
                                    Match IsEmail = rgxJetblueEmail.Match(ACMTailNum.ToUpper());

                                    if (IsEmail.Success)
                                    {
                                        msgTIMES_DELAY += "A subscription has been created for " + CommandSent +
                                                     ",,Updates to ETA and ETD will be delivered, to this email address for the next two hours.,";

                                        //Create Subscription
                                        ChucksStringHander CSH = new ChucksStringHander();
                                        tblAreqSubscription newsub = new tblAreqSubscription();

                                        newsub.CommandSent = CommandSent;
                                        newsub.AreqCommand = Command;
                                        newsub.SubActive = true;
                                        newsub.SubAddress = ACMTailNum;
                                        newsub.SubExpiriation = DateTime.Now + new TimeSpan(0, 120, 0);
                                        newsub.SubStartTime = DateTime.Now;
                                        newsub.SubType = "EMAIL";
                                        //Create a Hash of ETD and ETA to look for changes
                                        newsub.MD5Hash1 = CSH.CreateMD5Hash(FlightsResponse[x].CurrentDepartureDateTime.ToString()
                                            + FlightsResponse[x].CurrentArrivalDateTime.ToString());
                                        newsub.MD5Hash2 = CSH.CreateMD5Hash(FlightsResponse[x].DepartureDelayCode.ToString() + FlightsResponse[x].ArrivalDelayCode.ToString());

                                        using (new Impersonator("APP_AREQ2", "jetblue", "HappyJetting!10"))
                                        {
                                            using (ProdFltOpsDBDataContext db = new ProdFltOpsDBDataContext())
                                            {
                                                db.tblAreqSubscriptions.InsertOnSubmit(newsub);
                                                db.SubmitChanges();
                                            }
                                        }
                                    }
                                }
                            }
                    }
                        break;
                    default:
                        Debug.WriteLine("ERROR: Reached default case in TIMES_DELAY Request");
                        break;
                }
                return msgTIMES_DELAY;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ TIMES Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ TIMES Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_CREW_Req(string FltNumber, DateTime RequestDate, string ReplyEmail, string CommandSent)
        {
            try
            {
                ChucksStringHander CSH = new ChucksStringHander();
                Regex rgxJetblueEmail = new Regex(@".+@JETBLUE.COM", RegexOptions.Singleline);
                Match IsEmail = rgxJetblueEmail.Match(ReplyEmail.ToUpper());
                
                string msgCREW ="Flt: " + FltNumber + "," +
                                "Date: " + RequestDate.ToShortDateString() + ",,";

                ChucksClassLibrary.prodFlight_v3.FlightDetail[] OrigDestResp = ChucksWSH.prd_GetFlightsByFlightNumber_30("B6", FltNumber, "", "", ChucksCT.GetBeginningOfDay(RequestDate), ChucksCT.GetEndOfDay(RequestDate));

                if (OrigDestResp == null)
                {
                    msgCREW += "No data found for,";
                    msgCREW += "Flt: " + FltNumber ;
                }

                else if (OrigDestResp.Length == 1)
                {
                    ChucksClassLibrary.prodCrew_v3.FlightCrewmember[] CrewMember = ChucksWSH.GetFlightCrew_30("B6", OrigDestResp[0].DepartureAirport, OrigDestResp[0].ArrivalAirport, FltNumber, RequestDate);
                    if (CrewMember != null)
                    {
                        msgCREW += "ETD: " + OrigDestResp[0].CurrentDepartureDateTime.ToString("HHmm") + " L" + ",";
                        for (int x = 0; x < CrewMember.Length; x++)
                        {
                            string DeadHead = "  ";
                            if (Regex.Match(CommandSent, @"^SPCREW").Success)
                            {

                                bool allowed = 
                                    (ChucksMH.IsEmailInGroup(ReplyEmail, "ChiefPilots") ||
                                     ChucksMH.IsEmailInGroup(ReplyEmail, "BlueChkAmnE190") ||
                                     ChucksMH.IsEmailInGroup(ReplyEmail, "BlueChkAmnA320") ||
                                     ChucksMH.IsEmailInGroup(ReplyEmail, "Flight Ops Leadership") || 
                                     ChucksMH.IsEmailInGroup(ReplyEmail, "Flight Ops Team") || 
                                    (ReplyEmail == "CHARLES.COOK@JETBLUE.COM") || 
                                    (ReplyEmail == "BRIAN.NORTH@JETBLUE.COM"));
                                if (allowed)
                                {
                                    if (CrewMember[x].IsDeadHead == true) DeadHead = "DH";
                                    else DeadHead = "  ";
                                    if (IsEmail.Success)
                                        msgCREW += ",<a href=\"mailto:AREQ@jetblue.com?subject=AREQ PIC " + CrewMember[x].CrewmemberId + "\">" + CrewMember[x].CrewmemberId + "</a> " + CrewMember[x].Senority + " " + DeadHead + " " + CrewMember[x].Position + " - " + CrewMember[x].LastName + "." + CrewMember[x].FirstName;
                                    else
                                        msgCREW += "," + CrewMember[x].CrewmemberId + " " + CrewMember[x].Senority + " " + DeadHead + " " + CrewMember[x].Position + " - " + CrewMember[x].LastName + "." + CrewMember[x].FirstName;
                                    try
                                    {
                                        ChucksClassLibrary.prodCrew_v3.Phone[] CrewPhoneNumbers = ChucksWSH.GetCrewMemberPhoneNumbers_30(CrewMember[x].CrewmemberId);
                                        if (CrewPhoneNumbers != null)
                                        {
                                            for (int y = 0; y < CrewPhoneNumbers.Length; y++)
                                            {
                                                msgCREW += " " + CrewPhoneNumbers[y].Description + ": " + CrewPhoneNumbers[y].Number + " ";
                                            }
                                        }
                                    }
                                    catch (Exception err)
                                    {
                                        LogEvent("AREQ CREW Sub Phonenumbers Call, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                                    }
                                }
                                else //NOT ALLOWED
                                {
                                    msgCREW += "YOU ARE NOT AUTHORIZED FOR THIS REQUEST";
                                }
                            }
                            else if (Regex.Match(CommandSent, @"^DISPCREW").Success)
                            {
                                //FOR DISPCREW ONLY PRINT CA AND FO INFORMATION
                                bool allowed = (ChucksMH.IsEmailInGroup(ReplyEmail, "BlueDispatch") | (ReplyEmail == "CHARLES.COOK@JETBLUE.COM"));
                                if (allowed)
                                {
                                    if ((CrewMember[x].Position == "CA") || (CrewMember[x].Position == "FO"))
                                    {
                                        if (CrewMember[x].IsDeadHead == true) DeadHead = "DH";
                                        else DeadHead = "  ";
                                        if (IsEmail.Success)
                                            msgCREW += ",<a href=\"mailto:AREQ@jetblue.com?subject=AREQ PIC " + CrewMember[x].CrewmemberId + "\">" + CrewMember[x].CrewmemberId + "</a> " + DeadHead + " " + CrewMember[x].Position + " - " + CrewMember[x].LastName + "." + CrewMember[x].FirstName;
                                        else
                                            msgCREW += "," + CrewMember[x].CrewmemberId + " " + DeadHead + " " + CrewMember[x].Position + " - " + CrewMember[x].LastName + "." + CrewMember[x].FirstName;
                                        try
                                        {
                                            ChucksClassLibrary.prodCrew_v3.Phone[] CrewPhoneNumbers = ChucksWSH.GetCrewMemberPhoneNumbers_30(CrewMember[x].CrewmemberId);

                                            if (CrewPhoneNumbers != null)
                                            {
                                                msgCREW += " " + CrewPhoneNumbers[0].Description + ": " + CrewPhoneNumbers[0].Number + " ";
                                            }
                                        }
                                        catch (Exception err)
                                        {
                                            LogEvent("AREQ CREW Sub Phonenumbers Call, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                                        }
                                    }
                                }
                                else //NOT ALLOWED
                                {
                                    msgCREW += "YOU ARE NOT AUTHORIZED FOR THIS REQUEST";
                                }
                            }
                            else
                            {
                                if (CrewMember[x].IsDeadHead == true) DeadHead = "DH";
                                else DeadHead = "  ";
                                if (IsEmail.Success)
                                    msgCREW += ",<a href=\"mailto:AREQ@jetblue.com?subject=AREQ PIC " + CrewMember[x].CrewmemberId + "\">" + CrewMember[x].CrewmemberId + "</a> " + DeadHead + " " + CrewMember[x].Position + " - " + CrewMember[x].LastName + "." + CrewMember[x].FirstName;
                                else
                                    msgCREW += "," + CrewMember[x].CrewmemberId + " " + DeadHead + " " + CrewMember[x].Position + " - " + CrewMember[x].LastName + "." + CrewMember[x].FirstName;
                            }
                        }
                    }

                }
                else if (OrigDestResp.Length > 1)
                {
                    msgCREW += "Multiple Flights Found,";
                    for (int y = 0; y < OrigDestResp.Length; y++)
                    {
                            msgCREW += "," + OrigDestResp[y].DepartureAirport + "-" + OrigDestResp[y].ArrivalAirport + ",";
                            msgCREW += "ETD: " + OrigDestResp[y].CurrentDepartureDateTime.ToString("HHmm") + " L" + ",";

                            ChucksClassLibrary.prodCrew_v3.FlightCrewmember[] CrewMember = ChucksWSH.GetFlightCrew_30("B6", OrigDestResp[y].DepartureAirport, OrigDestResp[y].ArrivalAirport, FltNumber, RequestDate);
                           
                            if (CrewMember != null)
                            {
                                for (int w = 0; w < CrewMember.Length; w++)
                                {
                                    string DeadHead = "  ";
                                    if (Regex.Match(CommandSent, @"^SPCREW").Success)
                                    {
                                        bool allowed = 
                                            (ChucksMH.IsEmailInGroup(ReplyEmail, "ChiefPilots") ||
                                             ChucksMH.IsEmailInGroup(ReplyEmail, "BlueChkAmnE190") ||
                                             ChucksMH.IsEmailInGroup(ReplyEmail, "BlueChkAmnA320") ||
                                             ChucksMH.IsEmailInGroup(ReplyEmail, "FLTOPSDUTY") ||
                                            (ReplyEmail == "CHARLES.COOK@JETBLUE.COM") ||
                                            (ReplyEmail == "BRIAN.NORTH@JETBLUE.COM"));
                                        if (allowed)
                                        {
                                            if (CrewMember[w].IsDeadHead == true) DeadHead = "DH";
                                            else DeadHead = "  ";
                                            if (IsEmail.Success)
                                                msgCREW += ",<a href=\"mailto:AREQ@jetblue.com?subject=AREQ PIC " + CrewMember[w].CrewmemberId + "\">" + CrewMember[w].CrewmemberId + "</a> " + DeadHead + " " + CrewMember[w].Position + " - " + CrewMember[w].LastName + "." + CrewMember[w].FirstName;
                                            else
                                                msgCREW += "," + CrewMember[w].CrewmemberId + " " + DeadHead + " " + CrewMember[w].Position + " - " + CrewMember[w].LastName + "." + CrewMember[w].FirstName;  
                                            try
                                            {
                                                ChucksClassLibrary.prodCrew_v3.Phone[] CrewPhoneNumbers = ChucksWSH.GetCrewMemberPhoneNumbers_30(CrewMember[w].CrewmemberId);

                                                if (CrewPhoneNumbers != null)
                                                {
                                                    for (int z = 0; z < CrewPhoneNumbers.Length; z++)
                                                    {
                                                        msgCREW += " " + CrewPhoneNumbers[z].Description + ": " + CrewPhoneNumbers[z].Number + " ";
                                                    }
                                                }
                                            }
                                            catch (Exception err)
                                            {
                                                LogEvent("AREQ CREW Sub Phonenumbers Call, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                                            }
                                        }
                                        else //NOT ALLOWED
                                        {
                                            msgCREW += "YOU ARE NOT AUTHORIZED FOR THIS REQUEST";
                                        }
                                    }
                                    else if (Regex.Match(CommandSent, @"^DISPCREW").Success)
                                    {
                                        //FOR DISPCREW ONLY PRINT CA AND FO INFORMATION
                                        bool allowed = (ChucksMH.IsEmailInGroup(ReplyEmail, "BlueDispatch") | (ReplyEmail == "CHARLES.COOK@JETBLUE.COM"));
                                        if (allowed)
                                        {
                                            if ((CrewMember[w].Position == "CA") || (CrewMember[w].Position == "FO"))
                                            {
                                                if (CrewMember[w].IsDeadHead == true) DeadHead = "DH";
                                                else DeadHead = "  ";

                                                msgCREW += "," + CrewMember[w].CrewmemberId + " " + DeadHead + " " + CrewMember[w].Position + " - " + CrewMember[w].LastName + "." + CrewMember[w].FirstName;
                                                try
                                                {
                                                    ChucksClassLibrary.prodCrew_v3.Phone[] CrewPhoneNumbers = ChucksWSH.GetCrewMemberPhoneNumbers_30(CrewMember[w].CrewmemberId);
                                                    if (CrewPhoneNumbers != null)
                                                    {
                                                        for (int z = 0; z < CrewPhoneNumbers.Length; z++)
                                                        {
                                                            msgCREW += " " + CrewPhoneNumbers[0].Description + ": " + CrewPhoneNumbers[0].Number + " ";
                                                        }
                                                    }
                                                }
                                                catch (Exception err)
                                                {
                                                    LogEvent("AREQ CREW Sub Phonenumbers Call, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                                                }
                                            }
                                        }
                                        else //NOT ALLOWED
                                        {
                                            msgCREW += "YOU ARE NOT AUTHORIZED FOR THIS REQUEST";
                                        }
                                    }
                                    else
                                    {
                                        if (CrewMember[w].IsDeadHead == true) DeadHead = "DH";
                                        else DeadHead = "  ";
                                        msgCREW += "," + CrewMember[w].CrewmemberId + " " + DeadHead + " " + CrewMember[w].Position + " - " + CrewMember[w].LastName + "." + CrewMember[w].FirstName;
                                    }
                                }
                                
                            }
                    }
                }
                return msgCREW;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ CREW Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ CREW Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_LOADS_Req(string FltNumber, DateTime RequestDate, string ReplyEmail, string CommandSent)
        {
            try
            {
                string msgLoads = "Flt: " + FltNumber + "," +
                                 "Date: " + RequestDate.ToShortDateString() + ",";

                DateTime dtReqBegin = new DateTime(RequestDate.Year, RequestDate.Month, RequestDate.Day, 0, 0, 0, 0);
                DateTime dtReqEnd = new DateTime(RequestDate.Year, RequestDate.Month, RequestDate.Day, 23, 59, 59, 0);

                ChucksClassLibrary.prodFlight_v3.FlightDetail[] FlightResponse = ChucksWSH.prd_GetFlightsByFlightNumber_30("B6", FltNumber, "", "", dtReqBegin, dtReqEnd);
                if (FlightResponse == null)
                {
                    msgLoads += "No data found for,";
                    msgLoads += "Flt: " + FltNumber;
                }

                else if (FlightResponse.Length == 1)
                {
                    ChucksClassLibrary.prodFlight_v3.PassengerDetail[] respPax = ChucksWSH.prd_GetPaxDetails_30("B6", FlightResponse[0].DepartureAirport, FlightResponse[0].ArrivalAirport, FltNumber, RequestDate);
                    msgLoads += "," + "Equip: " + FlightResponse[0].Equipment + ",";
                    for (int x = 0; x < respPax.Length; x++)
                    {
                        if (respPax[x].PassengerGroup == "booked_pax")
                        {
                            msgLoads += "Booked PAX" + " : " + respPax[x].PassengerCount + ",";
                        }
                        else if (respPax[x].PassengerGroup == "booked_pad")
                        {
                            msgLoads += "Booked STBY" + " : " + respPax[x].PassengerCount + ",";
                        }
                        else if (respPax[x].PassengerGroup == "actual_pax")
                        {
                            msgLoads += "Actual PAX" + " : " + respPax[x].PassengerCount + ",";
                        }
                        else if (respPax[x].PassengerGroup == "actual_pad")
                        {
                            msgLoads += "Actual STBY" + " : " + respPax[x].PassengerCount + ",";
                        }
                    }
                    if (Regex.Match(CommandSent, @"^SPLOADS").Success)
                    {
                       // bool allowed = (ChucksMH.IsEmailInGroup(ReplyEmail, "ChiefPilots") || ChucksMH.IsEmailInGroup(ReplyEmail, "FLTOPSDUTY") || (ReplyEmail == "CHARLES.COOK@JETBLUE.COM"));
                       // if (allowed)
                       // {
                            msgLoads += ",STBY PAX:,";
                            ChucksClassLibrary.prodFlight_v3.Manifest[] response = ChucksWSH.prd_GetManifestDetails_30("B6", FlightResponse[0].DepartureAirport, FlightResponse[0].ArrivalAirport, FltNumber, RequestDate);
                            int counter = 1;
                            for (int x = 0; x < response.Length; x++)
                            {
                                if ((response[x].SSRCodes != null) && (response[x].SSRCodes.Contains("PASS")))
                                {
                                    msgLoads += counter + " " + response[x].PassengerName + "  " + response[x].RecordLocator + " " + response[x].SeatNumber + ",";
                                    counter++;
                                }
                            }
                        //}
                    }
                }
                else if (FlightResponse.Length > 1)
                {
                    msgLoads += ",Multiple Flights Found,";
                    for (int y = 0; y < FlightResponse.Length; y++)
                    {
                        msgLoads += "," + FlightResponse[y].DepartureAirport + "-" + FlightResponse[y].ArrivalAirport;
                        msgLoads += "," + "Equip: " + FlightResponse[y].Equipment + ",";
                        msgLoads += "ETD: " + FlightResponse[y].CurrentDepartureDateTime.ToString("HHmm") + " L" + ",";

                        ChucksClassLibrary.prodFlight_v3.PassengerDetail[] respPax = ChucksWSH.prd_GetPaxDetails_30("B6", FlightResponse[0].DepartureAirport, FlightResponse[0].ArrivalAirport, FltNumber, RequestDate);
                        for (int z = 0; z < respPax.Length; z++)
                        {
                            if (respPax[z].PassengerGroup == "booked_pax")
                            {
                                msgLoads += "Booked PAX" + " : " + respPax[z].PassengerCount + ",";
                            }
                            else if (respPax[z].PassengerGroup == "booked_pad")
                            {
                                msgLoads += "Booked STBY" + " : " + respPax[z].PassengerCount + ",";
                            }
                            else if (respPax[z].PassengerGroup == "actual_pax")
                            {
                                msgLoads += "Actual PAX" + " : " + respPax[z].PassengerCount + ",";
                            }
                            else if (respPax[z].PassengerGroup == "actual_pad")
                            {
                                msgLoads += "Actual STBY" + " : " + respPax[z].PassengerCount + ",";
                            }
                        }
                        if (Regex.Match(CommandSent, @"^SPLOADS").Success)
                        {
                          //  bool allowed = (ChucksMH.IsEmailInGroup(ReplyEmail, "ChiefPilots") || ChucksMH.IsEmailInGroup(ReplyEmail, "FLTOPSDUTY") || (ReplyEmail == "CHARLES.COOK@JETBLUE.COM"));
                          //  if (allowed)
                          //  {
                                msgLoads += ",STBY PAX:,";
                                ChucksClassLibrary.prodFlight_v3.Manifest[] response = ChucksWSH.prd_GetManifestDetails_30("B6", FlightResponse[0].DepartureAirport, FlightResponse[0].ArrivalAirport, FltNumber, RequestDate);
                                int counter = 1;
                                for (int x = 0; x < response.Length; x++)
                                {
                                    if ((response[x].SSRCodes != null) && (response[x].SSRCodes.Contains("PASS")))
                                    {
                                        msgLoads += counter + " " + response[x].PassengerName + "  " + response[x].RecordLocator + " " + response[x].SeatNumber + ",";
                                        counter++;
                                    }
                                }
                           // }
                                                    
                        }
                    }
                }
                
                return msgLoads;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ LOADS Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ LOADS Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_TAIL_Req(string TailNumber, DateTime RequestDate, string ACMTailNum, string CommandSent)
        {
            try
            {
                string msgTail = "Tail: " + TailNumber + ",";
                DateTime dtReq = DateTime.MinValue;

                if (RequestDate != DateTime.MinValue)
                {
                    dtReq = RequestDate;
                    msgTail += "Date: " + dtReq.ToShortDateString() + ",";
                }
                else
                {
                    dtReq = DateTime.Now;
                    msgTail += "Date: " + dtReq.ToShortDateString() + ",";
                }

                DateTime dtStart = new DateTime(dtReq.Year, dtReq.Month, dtReq.Day, 0, 0, 0, 0);
                DateTime dtEnd = new DateTime(dtReq.Year, dtReq.Month, dtReq.Day, 23, 59, 59, 0);

                ChucksClassLibrary.prodFlight_v3.FlightDetail[] TailResp = ChucksWSH.prd_GetFlightsByTail_30(TailNumber, dtStart, dtEnd);
                //ChucksClassLibrary.prodFlight_v2_1.FlightDetail[] TailResp = ChucksWSH.GetFlightDetailsByTail(dtStart, dtEnd, TailNumber);
                if (TailResp == null)
                {
                    msgTail += "No Flights Found for " + TailNumber + ", on " + dtReq.ToShortDateString() + ",";
                }
                else
                {
                    var query = from FlightDetail in TailResp
                                orderby FlightDetail.CurrentDepartureDateTime
                                select FlightDetail;

                    string DepartureTime = ""; string ArrivalTime = "";
                    msgTail += ",(S)=SCHEDULED (E)=ESTIMATED";
                    msgTail += ",FLT  PAIR    STATUS    (S)ETD   (S)ETA,";

                    foreach (var item in query)
                    {
                        if (item.CurrentDepartureDateTime != item.ScheduledDepartureDateTime)
                            DepartureTime = "(E)" + item.CurrentDepartureDateTime.ToString("HHmm") + "L";
                        else
                            DepartureTime = "(S)" + item.ScheduledDepartureDateTime.ToString("HHmm") + "L";

                        if (item.CurrentArrivalDateTime != item.ScheduledArrivalDateTime)
                            ArrivalTime = "(E)" + item.CurrentArrivalDateTime.ToString("HHmm") + "L";
                        else
                            ArrivalTime = "(S)" + item.ScheduledArrivalDateTime.ToString("HHmm") + "L";

                        msgTail += item.FlightNumber + " " +
                                   item.DepartureAirport + "-" +
                                   item.ArrivalAirport + " " +
                                   item.FlightStatus.PadRight(9, ' ') + " " +
                                   DepartureTime + " " +
                                   ArrivalTime + ",";
                    }
                }

                return msgTail;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ TAIL Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ TAIL Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string ParseACM_INBOUND_Req(string FltNumber, DateTime RequestDate, string ACMTailNum, string CommandSent)
        {
            try
            {
                string msgINBOUND = "Flt: " + FltNumber + ",";
                DateTime dtReq;

                if (RequestDate != DateTime.MinValue)
                {
                    dtReq = RequestDate;
                    msgINBOUND += "Date: " + dtReq.ToShortDateString() + ",";
                }
                else
                {
                    dtReq = DateTime.Now;
                    msgINBOUND += "Date: " + dtReq.ToShortDateString() + ",";
                }

                DateTime dtStart = new DateTime(dtReq.Year, dtReq.Month, dtReq.Day, 0, 0, 0, 0);
                DateTime dtEnd = new DateTime(dtReq.Year, dtReq.Month, dtReq.Day, 23, 59, 59, 0);

                ChucksClassLibrary.prodFlight_v3.FlightDetail[] FlightResponse = ChucksWSH.prd_GetFlightsByFlightNumber_30("B6", FltNumber, "", "", dtStart, dtEnd);
                List<string> lstTails = new List<string>();

                foreach (ChucksClassLibrary.prodFlight_v3.FlightDetail Flt in FlightResponse)
                        lstTails.Add(Flt.TailNumber);

                var uniqueTails = (from Tails in lstTails
                                   select Tails).Distinct();

                if (FlightResponse == null)
                {
                    msgINBOUND += " No flight data found";
                    return msgINBOUND;
                }

                foreach (string TailNumber in uniqueTails)
                {
                    ChucksClassLibrary.prodFlight_v3.FlightDetail[] TailResp = ChucksWSH.prd_GetFlightsByTail_30(TailNumber, dtStart, dtEnd);
                    if (TailResp == null)
                    {
                        msgINBOUND += "No Flights Found for " + TailNumber + ", on " + dtReq.ToShortDateString() + ",";
                    }
                    else
                    {
                        var query = from FlightDetail in TailResp
                                    orderby FlightDetail.CurrentDepartureDateTime
                                    select FlightDetail;

                        string DepartureTime = ""; string ArrivalTime = "";
                        msgINBOUND += ",Tail: " + TailNumber + ",";
                        msgINBOUND += ",(S)=SCHEDULED (E)=ESTIMATED";
                        msgINBOUND += ",FLT  PAIR    STATUS    (S)ETD   (S)ETA,";

                        foreach (var item in query)
                        {
                            if (item.CurrentDepartureDateTime != item.ScheduledDepartureDateTime)
                                DepartureTime = "(E)" + item.CurrentDepartureDateTime.ToString("HHmm") + "L";
                            else
                                DepartureTime = "(S)" + item.ScheduledDepartureDateTime.ToString("HHmm") + "L";

                            if (item.CurrentArrivalDateTime != item.ScheduledArrivalDateTime)
                                ArrivalTime = "(E)" + item.CurrentArrivalDateTime.ToString("HHmm") + "L";
                            else
                                ArrivalTime = "(S)" + item.ScheduledArrivalDateTime.ToString("HHmm") + "L";

                            msgINBOUND += item.FlightNumber + " " +
                                       item.DepartureAirport + "-" +
                                       item.ArrivalAirport + " " +
                                       item.FlightStatus.PadRight(9, ' ') + " " +
                                       DepartureTime + " " +
                                       ArrivalTime + ",";
                        }
                    }

                }

                return msgINBOUND;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ INBOUND Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ INBOUND Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static void ParseACM_EMAIL_TEXT(string[] arrACM, string ACMTailNum, string ACMFlightNum, string CommandSent)
        {
            try
            {
                switch (arrACM[0])
                {
                    case "EMAIL":
                        // Setup TEXT Notification EMail
                        MailMessage mail = new MailMessage();  //Create Mail Message Object
                        mail.To.Add(arrACM[1] + "@jetblue.com");

                        mail.Subject = "ACARS EMAIL From Flt: " + ACMFlightNum + " Tail: " + ACMTailNum;               // put subject here	
                        for (int x = 2; x < arrACM.Length; x++)
                        {
                            mail.Body += arrACM[x] + "\n"; // put body of email here
                        }
                        ChucksMH.SendMail(mail);
                        string msgEmailSent = "Your Email was sent to," +
                                              arrACM[1] + "@jetblue.com";
                        string[] arrEmailSent = Regex.Split(msgEmailSent, ",");

                        ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrEmailSent);
                        break;
                    case "TEXT":
                        //put text code here
                        MailMessage Textmail = new MailMessage();  //Create Mail Message Object
                        Textmail.To.Add("charles.cook@jetblue.com");

                        Textmail.Subject = "ACARS TEXT From Flt: " + ACMFlightNum + " Tail: " + ACMTailNum;               // put subject here	
                        for (int x = 2; x < arrACM.Length; x++)
                        {
                            Textmail.Body += arrACM[x] + "\n"; // put body of email here
                        }
                        //Add Reply Headers
                        Textmail.Body += "***ReplyStart\n\n***ReplyEnd\n"; // put body of email here

                        ChucksMH.SendMail(Textmail);
                        string msgTextSent = "Your TEXT was sent," +
                                              "successfully to:," +
                                              "charles.cook";
                        string[] arrTextSent = Regex.Split(msgTextSent, ",");

                        ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrTextSent);
                        break;
                }
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ EMAIL Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ EMAIL Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                string[] arrUnkERROR = Regex.Split(msgERROR, ",");
                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrUnkERROR);
            }
        }
        public static void ParseACM_ACARS_Req(string[] arrACM, string FltNumber, string ACMTailNum, string CommandSent)
        {
            try
            {
                string ACARS_Tail = "";
                string msgACARSReply = "";
                DateTime RequestDate = DateTime.Now;
                string msgACARS = "This is an ACARS message," +  //comma delim string to be split by reged
                                  "From AC: " + ACMTailNum + ",,";

                DateTime dtStart = new DateTime(RequestDate.Year, RequestDate.Month, RequestDate.Day, 0, 0, 0, 0);
                DateTime dtEnd = new DateTime(RequestDate.Year, RequestDate.Month, RequestDate.Day, 23, 59, 59, 0);

                ChucksClassLibrary.prodFlight_v3.FlightDetail[] FlightResponse = ChucksWSH.prd_GetFlightsByFlightNumber_30("B6", FltNumber, "", "", dtStart, dtEnd);

                if (FlightResponse == null)
                {
                    msgACARS += "No flight data found";
                }
                else if (FlightResponse.Length == 1)
                {
                    //One Flight Found
                    if ((FlightResponse[0].OutLocal != null) && (FlightResponse[0].InLocal == null))
                        {
                            //Found a flight that is OUT but not IN
                            ACARS_Tail = FlightResponse[0].TailNumber;
                            for (int y = 2; y < arrACM.Length; y++)
                            {
                                msgACARS += arrACM[y] + ",";
                            }

                            msgACARS += ",This ACARS message was," +  //comma delim string to be split by reged
                                        "sent by a BETA APP," +
                                        "written by Chuck Cook," +
                                        "?charles.cook@jetblue.com,";

                            string[] arrMsgACARS = Regex.Split(msgACARS, ",");
                            ChucksMH.SendACARSViaAIRCOM(ACARS_Tail, arrMsgACARS);

                            msgACARSReply = "Your ACARS Message was," +  //comma delim string to be split by reged
                                            "sent to AC: " + ACARS_Tail +
                                            ",Flt Num: " + FltNumber +
                                            ",,by a BETA APP written," +
                                            "by Chuck Cook," +
                                            "?charles.cook@jetblue.com,";
                        }
                        else //Flt found but not airborne
                        {
                            msgACARSReply += "Flt: " + FltNumber + " not airborne," +
                                             "This feature can only," +
                                             "send ACARS Msgs to AC," +
                                             "that are airborne";
                        }
                }
                else if (FlightResponse.Length < 1)
                {
                    msgACARSReply += "Flt: " + FltNumber + " not found,";
                }
                if (FlightResponse.Length > 1)
                {
                    msgACARSReply += "Multiple Flights Found,but none were airborne.";
                    for (int x = 0; x < FlightResponse.Length; x++)
                    {
                        if ((FlightResponse[x].OutLocal != null) && (FlightResponse[x].InLocal == null))
                            {
                            //Found a flight that is OUT but not IN
                            ACARS_Tail = FlightResponse[x].TailNumber   ;
                            for (int z = 2; z < arrACM.Length; z++)
                            {
                                msgACARS += arrACM[z] + ",";
                            }

                            msgACARS += ",This ACARS message was," +  //comma delim string to be split by reged
                                        "sent by a BETA APP," +
                                        "written by Chuck Cook," +
                                        "?charles.cook@jetblue.com,";

                            string[] arrMsgACARS = Regex.Split(msgACARS, ",");
                            ChucksMH.SendACARSViaAIRCOM(ACARS_Tail, arrMsgACARS);

                            msgACARSReply = "Your ACARS Message was," +  //comma delim string to be split by reged
                                            "sent to AC: " + ACARS_Tail +
                                            ",Flt Num: " + FltNumber +
                                            ",,by a BETA APP written," +
                                            "by Chuck Cook," +
                                            "?charles.cook@jetblue.com,";
                        }
                    } 
                }
                string[] arrMsgACARSReply = Regex.Split(msgACARSReply, ",");
                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrMsgACARSReply);
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ ACARS Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ ACARS Sub, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                string[] arrUnkERROR = Regex.Split(msgERROR, ",");
                ChucksMH.SendACARSViaAIRCOM(ACMTailNum, arrUnkERROR);
            }
        }
        /*
        public static string ParseACM_AIRPORT_Req(string INRAirport, string TurnTime, string ACMTailNum, string CommandSent)
        {
            DateTime TimeNow;
            DateTime TimeLater;
            try
            {
                if (TurnTime == "") TimeNow = DateTime.Now;
                else TimeNow = DateTime.ParseExact(TurnTime, "HHmm", null);

                if (TimeNow < (DateTime.Now - new TimeSpan(1, 0, 0))) TimeNow = TimeNow + new TimeSpan(24, 0, 0);  //Midnight Logic

                TimeLater = TimeNow + new TimeSpan(3, 0, 0);  //Grab flights for the next 3 hours

                string msgTURNS = "TURNS City:" + INRAirport + " Time: " + TimeNow.ToString("HHmm") + "L,,";

                ChucksClassLibrary.prodFlight_v2_1.FlightDetail[] OutBoundResp = ChucksWSH.GetFlightDetailsByRange(INRAirport, TimeNow, TimeLater, ChucksClassLibrary.prodFlight_v2_1.FlightDirection.DepartingFrom, ChucksClassLibrary.prodFlight_v2_1.FlightStatus.ALL);

                if (OutBoundResp != null)
                {
                    for (int x = 0; x < OutBoundResp.Length; x++)
                    {
                        string TailNum;
                        if (OutBoundResp[x].FlightStatus.ToString() == "CANCELLED") TailNum = "";
                        else TailNum = OutBoundResp[x].Tail;
                        msgTURNS = msgTURNS + OutBoundResp[x].ArrivalAirport + " F:" + OutBoundResp[x].FlightNumber + " " + OutBoundResp[x].FlightStatus + " " + OutBoundResp[x].CurrentDepartureDateTime.ToString("HHmm") + "L G:" + OutBoundResp[x].DepartureGate.Trim() + " T:" + TailNum + ",";
                    }
                }
                else
                {
                    msgTURNS = msgTURNS + "No Flights Found at " + INRAirport + ",between " + TimeNow.ToShortTimeString() + "-" + TimeLater.ToShortTimeString() + ",";
                }

                return msgTURNS;
            }
            catch (Exception err)
            {
                Console.WriteLine("AREQ TURNS Sub, You Sent: " + CommandSent + "Error: " + err.ToString());
                string LogFile = LogFileHeader + DateTime.Now.ToString("MMMyy") + ".txt";
                System.IO.File.AppendAllText(LogFile, DateTime.Now + ": " + CommandSent + err.ToString() + Environment.NewLine);

                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
         * */
        public static string[] CreatePREFLIGHT(string[] arrACM, DateTime RequestDate, string ReplyAddress, string CommandSent)
        {
            try
            {
                string msgPREFLIGHT = "";
                msgPREFLIGHT += ",,Preflight Brief for: " + arrACM[1] + ",,";

                //See if FltSum is available
                string FltSum = ParseACM_FLTSUM_Req(arrACM[1], RequestDate, ReplyAddress, CommandSent) + ",,";

                if (Regex.Match(FltSum, @"No release info found for Flt:").Success)
                {
                    msgPREFLIGHT += ParseACM_CREW_Req(arrACM[1], RequestDate, ReplyAddress, CommandSent) + ",,";
                    msgPREFLIGHT += ParseACM_INBOUND_Req(arrACM[1], RequestDate, ReplyAddress, CommandSent) + ",,";
                    msgPREFLIGHT += ParseACM_TIMES_DELAY_Req(arrACM[1], RequestDate, ReplyAddress, "TIMES", CommandSent) + ",,";
                    msgPREFLIGHT += ParseACM_LOADS_Req(arrACM[1], RequestDate, ReplyAddress, CommandSent) + ",,";
                    msgPREFLIGHT += FltSum;
                }
                else
                {
                    msgPREFLIGHT += FltSum;
                }

                string[] strarrPREFLIGHT = Regex.Split(msgPREFLIGHT, ",");
                return strarrPREFLIGHT;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ PREFLIGHT Request, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ PREFLIGHT Request, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                string[] arrMsgERROR = Regex.Split(msgERROR, ",");
                return arrMsgERROR;
            }
        }
        public static string[] CreateBRIEF(string[] arrACM, string ACMTailNum, string CommandSent)
        {
            try
            {
                string msgBRIEF = "This is a Brief for the following Airport(s): ";
                for (int x = 1; x < arrACM.Length; x++)
                {
                    msgBRIEF += arrACM[x] + " ";
                }
                msgBRIEF += ",,__________________________,";
                for (int x = 1; x < arrACM.Length; x++)
                {
                    msgBRIEF += ",,Brief for: " + arrACM[x] + ",,";
                    msgBRIEF += ParseACM_TURNS_Req(arrACM[x], "", "", CommandSent) + ",,";
                    msgBRIEF += ParseACM_TAXI_Req(arrACM[x], "", CommandSent) + ",,";
                    msgBRIEF += ParseACM_EDCTDELAYS_Req(arrACM[x], "", CommandSent) + ",,";
                    msgBRIEF += "__________________________,,";
                }
                string[] arrMsgBRIEF = Regex.Split(msgBRIEF, ",");
                return arrMsgBRIEF;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ BRIEF Request, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ BRIEF Request, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                string[] arrMsgERROR = Regex.Split(msgERROR, ",");
                return arrMsgERROR;
            }
        }
        public static string Scores(string[] arrACM, string ACMTailNum, string CommandSent)
        {
            //Gouge http://forum.xda-developers.com/showthread.php?t=272354
            //http://sports.espn.go.com/ncf/bottomline/scores
            try
            {
                ChucksWebServiceHandler CWH = new ChucksWebServiceHandler();

                string msgSCORES = "Scores for: ";
                for (int x = 1; x < arrACM.Length; x++)
                {
                    msgSCORES += arrACM[x] + " ";
                }
                msgSCORES += ",,__________________________,";
                for (int x = 1; x < arrACM.Length; x++)
                {
                   //ESPN Scores
                    string ESPNLeague = arrACM[x];
                    switch (arrACM[x])
                    {
                        case "COLFB":
                        case "NCAAF":
                            ESPNLeague = "ncf";
                            break;
                        case "COLBKB":
                        case "NCAAB":
                            ESPNLeague = "ncb";
                            break;
                    }
                    Regex rgxESPN = new Regex(@"left\d+=(?<Headline>.+?)&"); //Replace %20 with space, and ^ with nospace

                    string ESPNScrape = "";
                    if (arrACM[x] == "GOLF")
                        ESPNScrape = CWH.WebScraper("http://sports.espn.go.com/sports/" + ESPNLeague.ToLower() + "/bottomLineGolfLeaderboard", rgxESPN.ToString());
                    else
                        ESPNScrape = CWH.WebScraper("http://sports.espn.go.com/" + ESPNLeague.ToLower() + "/bottomline/scores", rgxESPN.ToString());
                    MatchCollection mcESPNScores = rgxESPN.Matches(ESPNScrape);
                    foreach (Match Score in mcESPNScores)
                    {
                        string ScoreMatch = Score.Groups["Headline"].Value;
                        ScoreMatch = Regex.Replace(ScoreMatch, @"%20", " ");
                        ScoreMatch = Regex.Replace(ScoreMatch, @"[,^]", string.Empty);  //Remove any comma's
                        msgSCORES += ScoreMatch + ",";
                    }

                   //YAHOO! Section
                    Regex rgxScores = new Regex(@"<title>(?<Headline>.+?)</title>");
                    string Scrape = CWH.WebScraper("http://sports.yahoo.com/" + arrACM[x].ToLower() + "/rss.xml", rgxScores.ToString());
                    MatchCollection mcScores = rgxScores.Matches(Scrape);
                    foreach (Match Score in mcScores)
                    {
                        string ScoreMatch = Score.Groups["Headline"].Value;
                        if ( ScoreMatch.ToUpper().StartsWith("YAHOO!") == false)
                        {
                            ScoreMatch = Regex.Replace(ScoreMatch, @",", string.Empty);  //Remove any comma's
                            msgSCORES += ScoreMatch + ",";
                        }
                    }

                    // UPI Section
                    //string UPILeauge = arrACM[x];
                    //switch (arrACM[x])
                    //{
                    //    case "COLFB":
                    //    case "NCAAF":
                    //        UPILeauge = "COL FB";
                    //        break;
                    //    case "COLBKB":
                    //    case "NCAAB":
                    //        UPILeauge = "COL BKB";
                    //        break;
                    //}
                    //msgSCORES += Regex.Replace(CWH.WebScraper("http://rss.upi.com/news/sports_news.rss", "<title>" + UPILeauge + ":(.|\n)*?</title>"), @"<(.|\n)*?>", string.Empty) + ",,";
                    //msgSCORES += "__________________________,,";
                }
                msgSCORES += "Try these: NFL NCAAF NCAAB MLB NHL TENNIS GOLF,";
                string msgSCORES2 = msgSCORES.Replace("\r\n", ",");
                return msgSCORES2;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ SCORES Request, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ SCORES Request, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string Stock(string[] arrACM, string ACMTailNum, string CommandSent)
        {
            try
            {
               // ChucksWebServiceHandler CWH = new ChucksWebServiceHandler();

                string msgSTOCK = "Quotes for: ";
                for (int x = 1; x < arrACM.Length; x++)
                {
                    msgSTOCK += arrACM[x] + " ";
                }
                msgSTOCK += ",__________________________,";
                for (int x = 1; x < arrACM.Length; x++)
                {
                    Quote q = new Quote();
                    q = q.StockQuote(arrACM[x]);
                    if (q != null)
                        msgSTOCK += string.Format("{0} {1} Lst:{2} Chg:{3}", q.Ticker, q.Date.ToString("MM/dd HHmm"), q.Last, q.Change) + ",";
                    else
                        msgSTOCK += "TICKER: " + arrACM[x] + " NOT FOUND,";
                }
                return msgSTOCK;
            }
            catch (Exception err)
            {
                Debug.WriteLine("AREQ STOCK Request, You Sent: " + CommandSent + "Error: " + err.ToString());
                LogEvent("AREQ STOCK Request, You Sent: " + CommandSent + "ERROR: " + err.ToString());
                string msgERROR = "You sent: " + CommandSent + "," + msgUnkERROR;
                return msgERROR;
            }
        }
        public static string GetDispPhone(string DeskNum)
        {
            string DispPhone = "";

            switch (DeskNum)
            {
                case "01":
                    DispPhone = "718-709-2451";
                    break;
                case "02":
                    DispPhone = "718-709-2452";
                    break;
                case "03":
                    DispPhone = "718-709-2453";
                    break;
                case "04":
                    DispPhone = "718-709-2454";
                    break;
                case "05":
                    DispPhone = "718-709-2455";
                    break;
                case "06":
                    DispPhone = "718-709-2456";
                    break;
                case "07":
                    DispPhone = "718-709-2457";
                    break;
                case "08":
                    DispPhone = "718-709-2458";
                    break;
                case "09":
                    DispPhone = "718-709-2459";
                    break;
                case "10":
                    DispPhone = "718-709-2460";
                    break;
                case "11":
                    DispPhone = "718-709-2461";
                    break;
                default:
                    DispPhone = "";
                    break;
            }
            return DispPhone;
        }
        public static void InitCounters()
        {
            objCounters cntemlDBSTATS = new objCounters()
            {
                CounterName = "emlDBSTATS",
                CurrentCount = 0
            };
            Counters.Add(cntemlDBSTATS);
            
            objCounters cntemlCRWBRIEF = new objCounters()
            {
                CounterName = "emlCRWBRIEF",
                CurrentCount = 0
            };
            Counters.Add(cntemlCRWBRIEF);

            objCounters cntCRWBRIEF = new objCounters()
            {
                CounterName = "CRWBRIEF",
                CurrentCount = 0
            };
            Counters.Add(cntCRWBRIEF);

            objCounters cntTWX = new objCounters()
            {
                CounterName = "TWX",
                CurrentCount = 0
            };
            Counters.Add(cntTWX);

            objCounters cntemlDUTY = new objCounters()
            {
                CounterName = "emlDUTY",
                CurrentCount = 0
            };
            Counters.Add(cntemlDUTY);
            objCounters cntDUTY = new objCounters()
            {
                CounterName = "DUTY",
                CurrentCount = 0
            };
            Counters.Add(cntDUTY);

            objCounters cntemlMOT = new objCounters()
            {
                CounterName = "emlMOT",
                CurrentCount = 0
            };
            Counters.Add(cntemlMOT);
            objCounters cntMOT = new objCounters()
            {
                CounterName = "MOT",
                CurrentCount = 0
            };
            Counters.Add(cntMOT);

            objCounters cntemlHOTEL = new objCounters()
            {
                CounterName = "emlHOTEL",
                CurrentCount = 0
            };
            Counters.Add(cntemlHOTEL);
            objCounters cntHOTEL = new objCounters()
            {
                CounterName = "HOTEL",
                CurrentCount = 0
            };
            Counters.Add(cntHOTEL);
            objCounters cntemlRAV = new objCounters()
            {
                CounterName = "emlRAV",
                CurrentCount = 0
            };
            Counters.Add(cntemlRAV);
            objCounters cntRAV = new objCounters()
            {
                CounterName = "RAV",
                CurrentCount = 0
            };
            Counters.Add(cntRAV);

            objCounters cntemlPREFLIGHT = new objCounters()
            {
                CounterName = "emlPREFLIGHT",
                CurrentCount = 0
            };
            Counters.Add(cntemlPREFLIGHT);
            objCounters cntPREFLIGHT = new objCounters()
            {
                CounterName = "PREFLIGHT",
                CurrentCount = 0
            };
            Counters.Add(cntPREFLIGHT);
            objCounters cntJBFLIGHTS = new objCounters()
            {
                CounterName = "JBFLIGHTS",
                CurrentCount = 0
            };
            Counters.Add(cntJBFLIGHTS);
            objCounters cntemlJBFLIGHTS = new objCounters()
            {
                CounterName = "emlJBFLIGHTS",
                CurrentCount = 0
            };
            Counters.Add(cntemlJBFLIGHTS);
            objCounters cntemlRLS = new objCounters()
            {
                CounterName = "emlRLS",
                CurrentCount = 0
            };
            
            Counters.Add(cntemlRLS);
            objCounters cntemlPIC = new objCounters()
            {
                CounterName = "emlPIC",
                CurrentCount = 0
            };
            Counters.Add(cntemlPIC);
            objCounters cntOPENT = new objCounters()
            {
                CounterName = "OPENT",
                CurrentCount = 0
            };
            Counters.Add(cntOPENT);
            objCounters cntemlOPENT = new objCounters()
            {
                CounterName = "emlOPENT",
                CurrentCount = 0
            };
            Counters.Add(cntemlOPENT);

            objCounters cntCOMMANDS = new objCounters()
            {
                CounterName = "COMMANDS",
                CurrentCount = 0
            };
            Counters.Add(cntCOMMANDS);
            objCounters cntemlCOMMANDS = new objCounters()
            {
                CounterName = "emlCOMMANDS",
                CurrentCount = 0
            };
            Counters.Add(cntemlCOMMANDS);

            objCounters cntSKED = new objCounters()
            {
                CounterName = "SKED",
                CurrentCount = 0
            };
            Counters.Add(cntSKED);
            objCounters cntemlSKED = new objCounters()
            {
                CounterName = "emlSKED",
                CurrentCount = 0
            };
            Counters.Add(cntemlSKED);

            objCounters cntPAIRING = new objCounters()
            {
                CounterName = "PAIRING",
                CurrentCount = 0
            };
            Counters.Add(cntPAIRING);
            objCounters cntemlPAIRING = new objCounters()
            {
                CounterName = "emlPAIRING",
                CurrentCount = 0
            };
            Counters.Add(cntemlPAIRING);

            objCounters cntFLTSUM = new objCounters()
            {
                CounterName = "FLTSUM",
                CurrentCount = 0
            };
            Counters.Add(cntFLTSUM);
            objCounters cntemlFLTSUM = new objCounters()
            {
                CounterName = "emlFLTSUM",
                CurrentCount = 0
            };
            Counters.Add(cntemlFLTSUM);

            objCounters cntTAIL = new objCounters()
            {
                CounterName = "TAIL",
                CurrentCount = 0
            };
            Counters.Add(cntTAIL);
            objCounters cntemlTAIL = new objCounters()
            {
                CounterName = "emlTAIL",
                CurrentCount = 0
            };
            Counters.Add(cntemlTAIL);

            objCounters cntLOADS = new objCounters()
            {
                CounterName = "LOADS",
                CurrentCount = 0
            };
            Counters.Add(cntLOADS);
            objCounters cntemlLOADS = new objCounters()
            {
                CounterName = "emlLOADS",
                CurrentCount = 0
            };
            Counters.Add(cntemlLOADS);

            objCounters cntBRIEF = new objCounters()
            {
                CounterName = "BRIEF",
                CurrentCount = 0
            };
            Counters.Add(cntBRIEF);
            objCounters cntemlBRIEF = new objCounters()
            {
                CounterName = "emlBRIEF",
                CurrentCount = 0
            };
            Counters.Add(cntemlBRIEF);

            objCounters cntPROGRAMS = new objCounters()
            {
                CounterName = "PROGRAMS",
                CurrentCount = 0
            };
            Counters.Add(cntPROGRAMS);
            objCounters cntemlPROGRAMS = new objCounters()
            {
                CounterName = "emlPROGRAMS",
                CurrentCount = 0
            };
            Counters.Add(cntemlPROGRAMS);

            objCounters cntEDCT = new objCounters()
            {
                CounterName = "EDCT",
                CurrentCount = 0
            };
            Counters.Add(cntEDCT);
            objCounters cntemlEDCT = new objCounters()
            {
                CounterName = "emlEDCT",
                CurrentCount = 0
            };
            Counters.Add(cntemlEDCT);

            objCounters cntSEDCT = new objCounters()
            {
                CounterName = "SEDCT",
                CurrentCount = 0
            };
            Counters.Add(cntSEDCT);
            objCounters cntemlSEDCT = new objCounters()
            {
                CounterName = "emlSEDCT",
                CurrentCount = 0
            };
            Counters.Add(cntemlSEDCT);

            objCounters cntTURNS = new objCounters()
            {
                CounterName = "TURNS",
                CurrentCount = 0
            };
            Counters.Add(cntTURNS);
            objCounters cntemlTURNS = new objCounters()
            {
                CounterName = "emlTURNS",
                CurrentCount = 0
            };
            Counters.Add(cntemlTURNS);

            objCounters cntTIMES = new objCounters()
            {
                CounterName = "TIMES",
                CurrentCount = 0
            };
            Counters.Add(cntTIMES);
            objCounters cntemlTIMES = new objCounters()
            {
                CounterName = "emlTIMES",
                CurrentCount = 0
            };
            Counters.Add(cntemlTIMES);

            objCounters cntTAXI = new objCounters()
            {
                CounterName = "TAXI",
                CurrentCount = 0
            };
            Counters.Add(cntTAXI);
            objCounters cntemlTAXI = new objCounters()
            {
                CounterName = "emlTAXI",
                CurrentCount = 0
            };
            Counters.Add(cntemlTAXI);

            objCounters cntDELAYS = new objCounters()
            {
                CounterName = "DELAYS",
                CurrentCount = 0
            };
            Counters.Add(cntDELAYS);
            objCounters cntemlDELAYS = new objCounters()
            {
                CounterName = "emlDELAYS",
                CurrentCount = 0
            };
            Counters.Add(cntemlDELAYS);

            objCounters cntCREW = new objCounters()
            {
                CounterName = "CREW",
                CurrentCount = 0
            };
            Counters.Add(cntCREW);
            objCounters cntemlCREW = new objCounters()
            {
                CounterName = "emlCREW",
                CurrentCount = 0
            };
            Counters.Add(cntemlCREW);

            objCounters cntSTOCK = new objCounters()
            {
                CounterName = "STOCK",
                CurrentCount = 0
            };
            Counters.Add(cntSTOCK);
            objCounters cntemlSTOCK = new objCounters()
            {
                CounterName = "emlSTOCK",
                CurrentCount = 0
            };
            Counters.Add(cntemlSTOCK);

            objCounters cntSCORES = new objCounters()
            {
                CounterName = "SCORES",
                CurrentCount = 0
            };
            Counters.Add(cntSCORES);
            objCounters cntemlSCORES = new objCounters()
            {
                CounterName = "emlSCORES",
                CurrentCount = 0
            };
            Counters.Add(cntemlSCORES);

            objCounters cntDOORS = new objCounters()
            {
                CounterName = "DOORS",
                CurrentCount = 0
            };
            Counters.Add(cntDOORS);
            objCounters cntemlDOORS = new objCounters()
            {
                CounterName = "emlDOORS",
                CurrentCount = 0
            };
            Counters.Add(cntemlDOORS);

            objCounters cntINBOUND = new objCounters()
            {
                CounterName = "INBOUND",
                CurrentCount = 0
            };
            Counters.Add(cntINBOUND);
            objCounters cntemlINBOUND = new objCounters()
            {
                CounterName = "emlINBOUND",
                CurrentCount = 0
            };
            Counters.Add(cntemlINBOUND);

            objCounters cntEMAIL = new objCounters()
            {
                CounterName = "EMAIL",
                CurrentCount = 0
            };
            Counters.Add(cntEMAIL);
            objCounters cntTEXT = new objCounters()
            {
                CounterName = "TEXT",
                CurrentCount = 0
            };
            Counters.Add(cntTEXT);
        }
        public static string[] DoAddHTMLTags(string[] arrMsg)
        {
            //Add HTML tags and CR to email body
            for (int x = 0; x < arrMsg.Count(); x++)
            {
                arrMsg[x] += "<br>";
            }
            return arrMsg;
        }
        public static string GetDelayDescriptions(string incomingDelayCode)
        {
            string strDelayCodeDescription = "";

            using (new Impersonator("APP_AREQ2", "jetblue", "HappyJetting!10"))
            {
                ProdFltOpsDBDataContext db = new ProdFltOpsDBDataContext();

                var varDelayCodes =
                    from foundDelays in db.tblDelayCodes
                    where foundDelays.DelayCode.Trim() == incomingDelayCode
                    select foundDelays;

                //where foundDelays.DelayCode.Trim() == incomingDelayCode
                if (varDelayCodes.Count() != 0)
                {
                    foreach (var row in varDelayCodes)
                    {
                        strDelayCodeDescription += row.DelayShortDesc + " - " + row.DelayExpandedDesc;
                    }
                    Debug.Write(" ");
                }
                else
                    strDelayCodeDescription += "No Description Found";
            }
            return strDelayCodeDescription;
        }

#endregion
        public static DateTime DateCompiled()
        {
            
            // Assumes that in AssemblyInfo.cs,
            // the version is specified as 1.0.* or the like,
            // with only 2 numbers specified;
            // the next two are generated from the date.
            // This routine decodes them.
            System.Version v =
            System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

            // v.Build is days since Jan. 1, 2000
            // v.Revision*2 is seconds since local midnight
            // (NEVER daylight saving time)

            DateTime t = new DateTime(
            v.Build * TimeSpan.TicksPerDay +
            v.Revision * TimeSpan.TicksPerSecond * 2
            ).AddYears(1999);

            if (DateTime.IsLeapYear(DateTime.Now.Year))
            {
                t = t + new TimeSpan(-1, 0, 0, 0);
            }

            if (TimeZone.IsDaylightSavingTime(DateTime.Now, TimeZone.CurrentTimeZone.GetDaylightChanges(DateTime.Now.Year)))
            {
                t = t + new TimeSpan(0, 1, 0, 0);
            }

            return t;
        }
    }
    class ObjState
    {
        protected internal String OutputFilename;
        protected internal String Filename;
    }
    class ACMREQHandler
    {
        public string[] AddACARSHeader(string Message)
        {

            string msgFooter = ",Questions?," +
                               "charles.cook@jetblue.com,," +
                               "**For COMMANDS LIST**," +
                               "AREQ COMMANDS";

            string newMessage = Message + msgFooter;

            string[] arrNewMessage = Regex.Split(newMessage, ",");
            return arrNewMessage;
        }
        public System.Net.Mail.MailMessage AddMailBody(string[] arrMessageBody, System.Net.Mail.MailMessage mail)
        {   
            //add Font tags
            //mail.IsBodyHtml = true;
            //mail.Body += "<p style=\"font-family:courier;font-size:12px;\">";
            for (int x = 0; x < arrMessageBody.Length; x++)
            {
                if (arrMessageBody[x] != null) mail.Body += arrMessageBody[x].ToUpper() + Environment.NewLine;//"<br>"; //
                else break;
            }
            //mail.Body += "</p>";
            return (mail);
        }
    }
    class objCounters
    {
        public string CounterName { get; set; }
        public int CurrentCount { get; set; }
    }
    class FileCompare : System.Collections.Generic.IEqualityComparer<FileData>
    {
        public FileCompare() { }

        public bool Equals(FileData f1, FileData f2)
        {
            return (f1.Name == f2.Name &&
                    f1.Size == f2.Size);
        }

        // Return a hash that reflects the comparison criteria. According to the 
        // rules for IEqualityComparer<T>, if Equals is true, then the hash codes must
        // also be equal. Because equality as defined here is a simple value equality, not
        // reference identity, it is possible that two or more objects will produce the same
        // hash code.
        public int GetHashCode(FileData fi)
        {
            string s = String.Format("{0}{1}", fi.Name, fi.Size);
            return s.GetHashCode();
        }
    }
}
